Reputation: 15
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
Upvotes: 0
Views: 278
Reputation: 14520
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
Upvotes: 2
Reputation: 351
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.
Upvotes: 2