Is there any way to makesure that the input from the user is all numbers?

Is there any way to makesure that the input from the user is all numbers?

thankz

if expr "$answer" : "[0-9]*$" > /dev/null ; then
echo 'all digits'
else
echo 'NOT all digits'
fi

thanks

what does the *$ after the [0-9] means ?
and what does > /dev/null means
i know that if i never put the > /dev/null , if all the user input is digits, it will display out now many digits are there.
can explain to me what does these means ?

thank you

This form of expr returns the number of characters in a string that match the specified pattern. In the following commands, the dot represents any single character, and the following asterisk means zero or more of that character:

expr XY : "X.*Y" (returns value of 2)
expr XabcY : "X.*Y" (returns value of 5)
expr XabcYdef : "X.*Y" (returns value of 5)

So the command:

if expr "$answer" : "[0-9]*$"

is looking for a digit, zero-or-more times, with nothing else following, because the $ means end-of-line or in this case end-of-string. And for expr, there is an implied beginning-of-line anchor.

Since you are not interested in seeing the number of characters that qualify, but only in the true/false result of the if-test, we discard the output of this command with the > /dev/null.

If the expression evaluates to one or more characters, it will return true, else will return false. So even though the asterisk allows zero-or-more occurrences in that position, a null answer evaluates to zero, thus false.

And if part of the pattern is enclosed in parentheses, if the entire expression evaluates true, instead of returning the number of characters that match the pattern, it will return the parenthesized part of that pattern. Example:

expr XabcYdef : "X\(.*\)Y"

returns "abc". That is a little hard to read because both the left and right parentheses must be preceeded with backslashes. Without the backslashes, it is easier to read:

expr XabcYdef : "X(.*)Y"

you can also do this...

let test_number=$input_number+1 2>number_error.txt

if test -s number_error.txt
then
echo "$input_number is NOT a number"
else
echo "$input_number is a number"
fi

:slight_smile: