Search code examples
linuxksh

Only allow numbers from standard input (read command)


i have a file that has a list of routes to .sh files, but to execute the scripts a date is needed, it the file the date is YYYYMMD. When I run the script that executes the list of scripts, i prompt the user for the date with the readcommand.

My problem is that i need to be 100% sure that the date that the user inputs is at least all numbers, how can i do this? i have already made sure that the maximum chars inputed is 8, so all i need is to only allow the user to input numbers. This is all i have so far.

echo 'Input date (YYYYMMDD)'
read -n 8 date

Any ideas?

Thankyou.


Solution

  • After having some help from @Thomas i have solved my problem. The solution is to compare the input varible to a regular expression. But for some reason doing this directly does not work, so i have saved the regular expression in a variable and then compared the variables.

    reg='^[0-9]{8}$'
    while [[ ! $number =~ $reg ]]
    do
     echo 'The format is wrong'
    done
    

    ^ <-- The start of the line

    [0-9]{8} <-- 8 numbers from 0 to 9

    $ <-- The end of the line

    =~ <-- Compare with regular expression

    Hope this answer helped!

    Thankyou

    PS: If anybody know why the comparison did not work when doing it directly please let me know.