Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash input validation during typing

Tags:

linux

bash

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.

like image 694
Dean Warren Powell Avatar asked Jan 22 '26 11:01

Dean Warren Powell


1 Answers

#/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}"
like image 54
Yuri G. Avatar answered Jan 25 '26 11:01

Yuri G.