Home > front end >  Bash script to add absolute values of numbers seperated by spaces
Bash script to add absolute values of numbers seperated by spaces

Time:11-09

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

CodePudding user response:

With Barmar's idea:

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

Output:

6

CodePudding user response:

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