5
with your third method will also execute 6 as a side effect.[…] which is better/simpler/clearer/efficient?
x=$(getconf LONG_MAX)
printf '%s\n' $((x + 1))
x=$(getconf LONG_MAX)
expr "${x:?Error: x is undefined.}" '+' '1'
Regarding your comment for option 3 I ran:Option 3 is conceptually wrong, it tries to execute the expansion of the arithmetic expression as a command. Just don't do that. Assuming you have an executable file 6 somewhere in your PATH (as nonsensical as this would be, it's perfectly possible!), trying to increment5
with your third method will also execute 6 as a side effect.
For the other two, I'd say you shouldn't waste any thought about "efficiency" comparing these. They both work without (expensive) calls to external tools, so it very much depends on the implementation of the shell.
As for clarity, I'd prefer the second option using the null-command, it's IMHO more readable.
I have always used the $() version and yes it works.and 4:
inc=`expr $inc + 1`
Thanks for the welcome.Welcome to the FreeBSD forums. It depends. What are you doing? Incrementing is hardly an exercise by itself. If it is not guaranteed that you stay within the 32‑bit range (the minimum range required to be supported by a POSIX‑compliant shell), you want to trigger some error.Bash:x=$(getconf LONG_MAX) printf '%s\n' $((x + 1))
This (possibly) prints a negative number, i. e. a wrong result , whereasBash:x=$(getconf LONG_MAX) expr "${x:?Error: x is undefined.}" '+' '1'
(possibly) fails with an overflow error message.
With the caveats above (if you are dealing with large numbers / wrap / 32bit systems), yes, option 2 is a perfectly reasonable choice, and preferable to 1 (less for the shell to process).I don't need large number capability for this and was interested to see if others could point out faults with option 2.
I prefer option 2 but wanted to check my understanding that it 'does nothing' with the substituted result(6 in the example above).
:
, to allow evaluations/expansions where a command would be expected, without causing any side effects. Of course, only use it if needed, e.g. something like:i=0
while [ $i -lt 10 ]; do
: $((i += 1))
echo $i
done
echo $((i += 1))
instead. expr
typically isn't a shell builtin, so using it always means forking a new process.