Reputation: 13
Here is my current code:
for i do
sum=$(expr $sum + $i)
done
echo =$sum
Now this works, but I want it to display all of the numbers. For example, If I enter ./sum 1 2 3, I want it to display 1+2+3=6. Right now it only displays the answer. Also, is there a way I could execute the file without ./. For instance, could I use sum 1 2 3 instead of ./sum 1 2 3. I've tried chmod 700 "myfile," but that didn't seem to work.
Upvotes: 0
Views: 166
Reputation: 289495
What about this?
while (( $# > 1 )); do
printf "$1 + "
sum=$((sum + $1 ))
shift
done
echo "$1 = $((sum + $1))"
It loops through the arguments you provide and adds them into the variable $sum
. For stylistic purposes I use printf
and finally echo
to have everything in the same line.
The usage of shift
is explained here:
The
shift
builtin command is used to "shift" the positional parameters by the given number n or by 1, if no number is given.
$ sh script.sh 1 2 3
1 + 2 + 3 = 6
$ sh script.sh 1 2 3 4 5
1 + 2 + 3 + 4 + 5 = 15
Upvotes: 1
Reputation: 785
Here a solution without loops:
numbers=$( printf -v str '%s+' $@; printf '%s' "${str%+}" )
sum=$(( $numbers ))
echo $numbers=$sum
the first line joins the input arguments with +, the second line calculates the sum and the third line outputs the equation
as to the second part of your question. Just put the script somewhere in your path (for example /usr/local/bin)
Upvotes: 0
Reputation: 530920
You can use IFS
and $*
to join all the arguments with +
:
(IFS="+"; printf '%s' "$*")
sum=0
for i; do
sum=$((sum + i))
done
printf '=%d\n' "$sum"
To run without the ./
prefix, you need to put the program in a directory that appears in your PATH
. Unless this is intended for people other than you, you should create a bin
directory in your home directory, then add this to your .bash_profile
:
PATH=~/bin/:$PATH
so that your bin
directory is added to the list of places to look for commands.
Upvotes: 1
Reputation: 38121
Another answer:
sum=0
for i in $@
do
sum=$(($sum + $i))
done
echo $sum
Upvotes: 0