0

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

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
Jimmy
  • 15
  • 1
  • 5
  • Did you mean to tag this with "bash" instead of "base"? – Eric Renouf Aug 08 '15 at 01:24
  • Unless you have some compelling reason, I suggest you not try to program in bash. bash/sh have grown well beyond their original capabilities and you pay for it in very arcane syntax. People more often script Python now where they would have used sh/bash or Perl in the past. For some tasks the shell is fine; it is hard to do `ls -lt | head -10 | awk '{print $2}'` more concisely. For things like addition, it's a bit irksome. – msw Aug 08 '15 at 01:49

2 Answers2

2

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.

Community
  • 1
  • 1
Gene
  • 311
  • 1
  • 10
2

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
Eric Renouf
  • 13,950
  • 3
  • 45
  • 67