Issue
I want to use $* in a loop but the first argument is ignored.
in other words:
sum=0
for i in $*
do
if [ $1 = "+" ]; then
sum=$(($sum+$i))
fi
done
echo $sum
Solution
To remove the first parameter, use shift
.
But before you shift, you should store the value somewhere.
As the first parameter doesn't change, you can check it just once before starting the loop:
#! /bin/bash
op=$1
shift
if [ "$op" = + ] ; then
sum=0
for i in $* ; do
sum=$(($sum+$i))
done
echo $sum
fi
Note that you don't need the quotes around +
. You should quote the $op
in the condition, though, to prevent parsing errors (try running the script specifying an empty string ""
as the first argument).
When using $((
, note that you can use shorter and faster way to increment a variable:
((sum+=i))
Answered By - choroba Answer Checked By - David Goodson (WPSolving Volunteer)