Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

let vs expr vs double parenthesis arithmetic in shell

When I was first learning shell scripting, a lot of examples I saw used let for basic arithmetic, but later I found out that some environments don't present let as a built-in, but support use of expr 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 let and one for expr) 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.

like image 516
Haravikk Avatar asked Mar 13 '14 19:03

Haravikk


1 Answers

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

like image 116
chepner Avatar answered Sep 19 '22 05:09

chepner