3

I'm writing Bash script that requires you to enter numbers only. How do I prevent non-numbers from being displayed as they are typed? For example, if I type 123ab45c6 at the prompt, only 123456 should be appear on the screen.

1
  • I edited the question a little to clean up the grammar and remove "kind regards" and other extraneous parts. I also added an example to help clarify you're asking. Please correct it if I got your meaning wrong. Commented Jun 30, 2015 at 2:14

1 Answer 1

2
#/bin/bash
echo "Please enter a number"
# variable to store the input
number=""
# reading in silent mode character by character
while read -s -n 1 c
do
    case $c in
    [0-9]) 
        # if the read character is digit add it to the number and print the number
        number="${number}${c}"
        echo -en "\r${number}"
        ;;      
    '') 
        # break on ENTER
        echo    
        break;; 
    esac
done
echo "You entered a number ${number}"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.