简体   繁体   中英

Linux Shell if-statements

I am trying to write a script to add integers together. My first script works to add numbers

for number in $@; do
sum=$(($sum + $number))
done

echo $sum

Now I am trying to write an if statement that checks if $number is an valid integer and if not display an error message and kill the script.

if [ -z $number]; then
sum=$(($sum + $number))
else
echo $number
echo "Sorry, $number is not a number"
exit
fi

I have been trying to figure this out for a few hours and keep getting stuck and help would be nice

The -z operator doesn't check if the string is a number, it checks if the length of the string is zero.

There isn't an operator to check if a string is an integer, however there are several ways to do this in bash. The answers on this previous discussion should be helpful .

the -z test will just test of the variable is empty (zero length) or not. If you want to know that is has an integer you could use a regex match like

if [[ $number =~ ^-?[0-9]+$ ]]; then
    sum=$((sum + number))
else
    echo "Sorry, $number is not a number"
    exit
 fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM