-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

23908938
  • 51
  • 1
  • 8

1 Answers1

-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.

Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17