2

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
starball
  • 20,030
  • 7
  • 43
  • 238
Steve Zee
  • 71
  • 5

3 Answers3

4

With Barmar's idea:

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

Output:

6
Cyrus
  • 84,225
  • 14
  • 89
  • 153
3

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
M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17
2

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
Léa Gris
  • 17,497
  • 4
  • 32
  • 41