This snippet of code has been taken from a larger script, (humbly) simulating the non-existing abs()
function:
[[ $(echo "$val < 0" | bc) -eq 1 ]] && val=$(echo "$val * -1" | bc)
So we test the number whether it is negative; if yes the second statement after the &&
will be executed.
This was my original line.
Some other SE user later changed this into:
(( $(bc <<<"$val < 0") == 1 )) && val=$(bc <<<"$val * -1")
OK, though both of these apparently work, I still prefer mine as it does not only make use of the -eq
operator (which has been implemented especially for non-strings) but it also avoids here-strings, which makes the code work better on read-only environments. (Keep in mind that /tmp
MUST be writeable for here-strings to work.)
Lastly, I seem to remember that bc
in the later line will output a true integer, which makes the use of ==
rather questionable, since this is only recommended to be used for strings.
Unfortunately bc
does not reveal in its man
page either whether it outputs its results as plain numbers or strings.
Opinions?
abs=${val#-}
? – choroba Apr 17 '15 at 15:33bash
old-schooler and still not too familiar with the "modern"${...#...}
syntax using brace substitution. – syntaxerror Apr 17 '15 at 15:34ksh
supportsabs(x)
in arithmetic contexts. – Janis Apr 17 '15 at 15:51