This article: Determine whether the user input parameter is a number
How is the calculation done in the shell?
Way One
[[email protected] scripts]# echo $((1+2)) 3
Way Two
Note: When using the method two, the requirements must be spaced. If you are using multiplication, the number must be escaped to write as \
How can I tell if the value entered by a user is a numeric character?
First of all, let's look at the use of Echo to calculate the time, the character + number will be what effect.
[[email protected] scripts]# echo $((a+1))1[[email protected] scripts]# echo $((a+2))2
In this case, the shell will calculate the character as zero, if we want to determine whether the user input is a number, then you can use the echo $ ((variable + 1)) to determine, if 1, then the user input is a character, if the number, then the result is not 1.
But this would be a problem, if the user entered a number of 0?
How to use two solutions
[[email protected] scripts]# expr b + 3expr: 非数值参数
Assuming that the user enters a parameter that is a character, then the use of expr will fail to calculate, when $? It's not 0, so we just need to see $? Whether it is 0 determines whether the parameter entered by the user is a number.
Example
"' #!/bin/bash-
Read-p "Please enter a number:" Number
Expr $number + 1 >/dev/null 2>&1
[$?-ne 0] && echo "$number is not number" | | echo "$number is a number"
**执行结果**
[Email protected] scripts]# bash intnumber.sh
Please enter a number:1
1 is a number
[Email protected] scripts]# bash intnumber.sh
Please enter a number:a
A is not number
版权所有:[arppinging](www.arppinging.com)
The "shell" Linux shell determines whether the variable entered by the user is a number