I want to take arguments from command line and print the sum of the integer. But if there is no argument given then it should give me total as 0.
Example vi sum.sh contains below code
total=0
for i in $@; do
(( total =i ))
done
echo "The total is $total"
bash sum.sh
Then this should give me output as 0
Similarly if I give bash sum.sh 1 2
then output coming as 3 which is correct but its not working when there is no arguments given.
I am getting error total: command not found
.
CodePudding user response:
Try this:
total=0
for i in $@; do
total=$(($total $i ))
done
echo "The total is $total"
When you use the value of a variable, it needs to be preceded by a dollarsign.
In top of that, you need $((...))
to perform calculations.
Edit: example
I have put this piece of script in a file, called test.sh
and did the following test (with its result):
Prompt> sh test.sh 1 2 6
The total is 9