Home > Software design >  how to add the value of the next argument to the previous one and print it out
how to add the value of the next argument to the previous one and print it out

Time:09-04

#!/bin/bash

#ARguments
ARG1=$1
ARG2=$2
ARG3=$3
ARG4=$4
ARG5=$5
ARG6=$6
ARG7=$7

echo $ARG1   $ARG2; $ARG2   $ARG3; $ARG3   $ARG4; $ARG4   $ARG5; $ARG5   $ARG6; $ARG6   $ARG7; $ARG7   $ARG1  #incorrect line
#context to explain

CodePudding user response:

One way to do this is shifting the patameters. This way you can echo the sum after every parameter.

    #!/bin/bash
    sum=0
    while [ -n "$1" ]; do   #while $1 exists
        let sum =$1
        echo $sum
        shift               #eliminates $1 and shifts the remaining parameters
    done
    #or echo the sum just at the end
    #echo $sum 

CodePudding user response:

More straightforward way is to use "foreach" or arithmetic "for" loop, instead of the while loop. This approach also avoid the side effect of removing the original parameters, in case they will be needed later.

Using: foreach

sum=0
for item ; do
    sum=$((sum item))
done
echo $sum

The arithmetic for can create code that is more similar to "c":

for ((sum=0, i=1 ; i<=$# ; i   )) ; do
    let sum=sum ${!i}
done
echo $sum

As one-liners: Or as one-liner:

# foreach
sum=0 ; for item ; do  sum=$((sum item)) ; done ; echo $sum
# Arithmetic for
for ((sum=0, i=1 ; i<=$# ; i   )) ; do let sum=sum ${!i} ; done ; echo $sum
  •  Tags:  
  • bash
  • Related