0
if test $# -lt 1
then
        echo "Please input a valid amount of numbers. Need at least one."
        exit 1
else
        args=0
        while args -eq "$#"; do
                echo $args
                shift
        done
fi

echo $sum
echo $n

The error I'm receiving is

./whileParamList: 15: ./whileParamList: args: not found

The while loop will increment to the previous parameter with a +=

Chris Zog
  • 15
  • 2
  • 7

2 Answers2

3

Bash isn't designed for numerical calculations. It's an orchestrator, not a "language" in the sense that C or Python is. See more detail:


The way I would do this would be something like:

mysum() (
  IFS=+
  bc<<<"$*"
)

Or perhaps:

mysum() (
  IFS=+
  echo "$(($*))"
)

Then call it like so:

$ mysum 5 89 83 7 0 2
186
Wildcard
  • 35,316
  • 26
  • 130
  • 258
2

Something like this i think it is ok:

if [[ $# -lt 1 ]]
then
        echo "Please input a valid amount of numbers. Need at least one."
        exit 1
else
        n=$#
        sum=0
        for arg in "$@"
        do
          echo "$arg"
          sum=$(($sum+$arg))
        done
fi

echo "sum=$sum"
echo "number of parameters=$n"

If you prefer the parameter shift method, this also work:

if [[ $# -lt 1 ]]
then
        echo "Please input a valid amount of numbers. Need at least one."
        exit 1
else
        n=$#
        sum=0
        while [[ $# -ne 0 ]];
        do
          echo "arg=$1"
          sum=$(($sum+$1))
          shift
        done
fi

echo "sum=$sum"
echo "number of parameters=$n"
George Vasiliou
  • 7,803
  • 3
  • 18
  • 42
  • @ChrisZog Updated. Offcourse you can use the test method in `if then else` if you prefer so. – George Vasiliou Jan 31 '17 at 00:57
  • 1
    This code may *work* but it is unidiomatic in the extreme. Bash is not C. Use pipes, globs, [IFS](http://unix.stackexchange.com/a/341359/135943), and avoid explicit loops and index variables wherever possible. Also, you don't need an "else" after "exit 1"; just put a "fi" and go forward. – Wildcard Jan 31 '17 at 03:07