Bash script to sum absolute values?

Viewed 4094

Is it possible to sum absolute values for integers entered into stdin and print the result to stdout?

So far I have is this:

read X
read Y
echo "$(($X+$Y))"

Can return:

11
11
22

But looking to get a result for absolutes. E.g:

-11
11
22
2 Answers

Consider modified version, working on modern bash.

With temporary variable - note expression on let must be quoted, otherwise the special characters '<' will break the expression logic.

read x
read y
let s="(x<0?-x:x)+(y<0?-y:y)"
echo "SUM(abs($x)+abs($y))=$s"

Or without intermediate variable, using the '$((expr))' grammar. No need to quote.

read x
read y
echo "SUM(abs($x)+abs($y))=" "$(((x<0?-x:x)+(y<0?-y:y)))"

Just strip the leading - from the variables:

read x
read y
echo "$((${x#-} + ${y#-}))"

This works since numbers in Bash are represented as strings.

Note that you should validate the user input (so the sign removal could be done there).

Related