SoFunction
Updated on 2025-03-09

Example of shell script to determine whether the input parameter is an integer value

When writing scripts, there are usually many judgments about command line parameters, variables, etc., whether they exist or whether they are of the correct type. When determining whether a value is received from the command line and needs to determine whether it is an integer value, there are two methods:

1. Use the shell command to calculate it with an integer value, and use $? to determine whether it is an integer value.

flag=true
read -p "please input a number:" num
while $flag
do
   expr $num + 0 &>/dev/null
   [ $? -eq 0 ] && flag=false || read -p "please input a integer:" num
done

2. Use sed to judge

flag=true
read -p "please input a number:" num
while $flag
do
  len=`echo "$num"|sed 's/[0-9]//g'|sed 's/-//g'`
  [ -n $len ] && flag=false || read -p "please input a integer:" num
done

The above example of determining whether the input parameters are integer values ​​in the shell script is all the content I share with you. I hope you can give you a reference and I hope you can support me more.