- Jan 18, 2002
- 5,893
- 0
- 76
I've been working on this script for several days trying to get it right (this is on Solaris) and every time I change something, it breaks something else. It has to add 4 integers and print out the result, while printing an error message if one of the 4 arguments is not an integer. I think the whole problem is where I try to determine if something is an integer or not using expr and a regular expression. I'm sure someone here has more experience with shell scripting than I do and can help me figure out what I'm not doing right. Any help is very much appreciated.
This is what I've got so far...
#!/bin/sh
sum=0
toAdd=4
if [ $# != $toAdd ]; then
echo "Usage: ./add4.sh int int int int"; echo
exit 1
fi
while [ $# -gt 0 ]
do
x=`expr "$1" : "[\-?][0-9]+\$"`
if [ $? = 1 ]; then
echo "Invalid argument."
exit 2
else
sum=`expr $sum + $1`
shift
fi
done
echo "The sum is: $sum"; echo
Thanks for any help.
This is what I've got so far...
#!/bin/sh
sum=0
toAdd=4
if [ $# != $toAdd ]; then
echo "Usage: ./add4.sh int int int int"; echo
exit 1
fi
while [ $# -gt 0 ]
do
x=`expr "$1" : "[\-?][0-9]+\$"`
if [ $? = 1 ]; then
echo "Invalid argument."
exit 2
else
sum=`expr $sum + $1`
shift
fi
done
echo "The sum is: $sum"; echo
Thanks for any help.
