Haravikk Haravikk - 2 years ago 213
Bash Question

let vs expr vs double parenthesis arithmetic in shell

When I was first learning shell scripting, a lot of examples I saw used

for basic arithmetic, but later I found out that some environments don't present
as a built-in, but support use of
instead (though it's significantly slower).

However, it is also possible in many shells to use double parentheses to perform arithmetic, for example
$((54 + 102))

Since I'm writing a script for portability, this presents a minefield of possibilities; currently I'm using two different wrapper functions (one for
and one for
) and using a quick test to decide which one to use in the rest of my script.

Anyway, what I'd like to know is if anyone can clarify the compatibility of each of these three arithmetic commands (and any others I've missed). I'm hoping that the double parentheses form may be common enough that I can just ditch compatibility checks, but it's a hard thing to search for so I decided to just come here and ask to find out for sure.

Just to note I'm only interested in regular arithmetic, I think I've already covered the few big-integers I (may) need to work with.

Answer Source

$(( ... )) is defined in the POSIX standard, which is probably as portable as you need to be.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download