Search code examples
bashsumabsolute-value

Bash script to add absolute values of numbers seperated by spaces


I need a bash script to find the sum of the absolute value of integers separated by spaces. For instance, if the input is:

1 2 -3

the script should print 6 to standard output I have:

while read x ; do echo $(( ${x// /+} )) ; done

which gives me

0

Without over complicated things, how would I include an absolute value of each x in that statement so the output would be:

6

Solution

  • You have almost done it, but the -s must have been removed from the line read:

    while read x; do x=${x//-}; echo $(( ${x// /+} )); done