Bash validating input while typing

I am writing a Bash script that only requires numbers to be entered. How do I prevent non-zero numbers from being displayed as I type them? For example, if I type 123ab45c6

in an invitation, only the 123456

.

+3


source to share


1 answer


#/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}"

      



+2


source







All Articles