Issue
This is the code:
sum=0
i=1
while [ $i -le $# ]
do
if [[ $i =~ ^[0-9]+$ ]];
then
sum=$(($sum+$(eval echo '$'$(eval echo ${i}))))
echo "$(eval echo '$'$(eval echo $i)) is number"
i=$((i+1))
else
echo "$(eval echo '$'$(eval echo $i)) is not a number"
i=$((i+1))
fi
done
echo "sum is $sum"
and this is the output when I try to distinguish b/w numbers and characters:
$ bash sumOfGivenNums.sh 3 4 3 a
3 is number
4 is number
3 is number
a is number
sum is 10
Solution
You've got a lot of really unnecessary code in your script; you almost never want to use the eval
function. I would probably write something like this:
sum=0
for arg in "$@"; do
if [[ $arg =~ ^[0-9]+$ ]]; then
echo "$arg is a number"
(( sum += arg ))
else
echo "$arg is not a number."
fi
done
echo "sum is $sum"
Answered By - larsks