2

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
Aserre
  • 4,916
  • 5
  • 33
  • 56
3.14 THON
  • 37
  • 2
  • 7

2 Answers2

2

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)))"
dash-o
  • 13,723
  • 1
  • 10
  • 37
1

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).

gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104