18

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.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Haravikk
  • 3,109
  • 1
  • 33
  • 46

1 Answers1

12

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

chepner
  • 497,756
  • 71
  • 530
  • 681
  • Hmm, in that case has it always been in the POSIX standard, any common shell environments that aren't POSIX compliant? Seems strange that we'd have `expr` if double parenthesis does practically everything that it does but a lot faster. – Haravikk Mar 14 '14 at 10:00
  • 2
    `expr` pre-dates the POSIX standard, from a time when the shell left all but the most basic functionality to external programs to implement. My understanding is that Solaris uses the Bourne shell (the original `sh`, not the identically named POSIX shell) as the default system shell, but it's not installed as `/bin/sh`, and a POSIX shell is still available at some path name. – chepner Mar 14 '14 at 12:34