Method 1: Use expr to calculate the sum of the variable and an integer. If normal execution is performed, the variable is an integer. Otherwise, an error occurs. $? The value is not 0.
Expr $ args + 0 &>/dev/null
Method 2: print the variable with sed replacement. Replace the number in the variable with null. If the variable is empty after replacement, it is an integer.
Echo $ args | sed's/[0-9] // G'
If a negative number is determined, use sed to filter the negative number.
Echo $ args | sed's/[0-9] // G' | sed's/-// G'
The following script uses two functions to determine the value. The code is very simple, so no comments are added.
#!/bin/bashusage(){cat <<EOFUSEAGE:sh $0args1 args2exit 1EOF}checkInt(){expr $1+ 0&>/dev/null[ $? -ne 0] && { echo "Args must be integer!";exit 1; }}checkInt1(){tmp=`echo $1|sed 's/[0-9]//g'`[ -n "${tmp}"]&& { echo "Args must be integer!";exit 1; }}[ $# -ne 2]&&usageargs1=$1args2=$2checkInt $args1checkInt1 $args2if[ $args1 -gt $args2 ];thenecho "yes,$args1 greate than $args2"elseecho "no,$args1 less than $args2"fi
This article is from the "gccmx163.com" blog, please be sure to keep this source http://489381.blog.51cto.com/479381/1331256