Bash script to add absolute values of numbers seperated by spaces

Viewed 258

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
3 Answers

With Barmar's idea:

echo "1 2 -3" | tr -d - | tr ' ' '+' | bc -l

Output:

6

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

POSIX friendly implementation without running a loop and without spawning a sub-shell:

#!/usr/bin/env sh

abssum() {
  IFS='-'
  set -- $*
  IFS=' '
  set -- $*
  IFS=+
  printf %d\\n $(($*))
}

abssum 1 2 -3

Result:

6
Related