-1

basically writing a script that adds numbers supplied by user as arguments to the script. The number of arguments are unknown. Also have to check to make sure it is an int. The script should show result of numbers.

an example:

./addNumbers 10 5 10

sum is 25

1
  • #!/bin/bash # check if more than 1 argument has been supplied by the user. if[ $# -lt 1 ] then Commented Apr 8, 2018 at 20:12

1 Answer 1

-1

Here you go:-

sum=0 if [ $# -eq 0 ]; then echo "Not enough arguments provided" echo "Correct uses : $0 23 22 25" echo "You can provide any number of argument" exit 1 fi while [ $# -gt 0 ] do echo "$1" sum=$(($sum+$1)) shift done echo "sum is $sum" 

Now you can try like:-

./addNumbers 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ....... 100 

Here line 1 is a variable setting sum to 0. Line 2 is checking to make sure there is a greater number than 0. Then you echo the first argument second argument etc. Every iteration it will print next argument from the argument list.

Sign up to request clarification or add additional context in comments.

10 Comments

This will only work if exactly 9 arguments are supplied.
@GordonDavisson, Thanks for your comment. I have modified my answer.
thanks! Just to clarify, line 1 is a variable setting sum to 0. line 2 is checking to make sure theres a greater number than 0. then you echo the first argument ? i just want to understand this better.
Yes true. I have added your comment in my answer so that other people also can understand this.
Thank you!! & another question.. say the user doesnt provide any arguments. I want it to reply back with a message
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.