💾 Archived View for thrig.me › blog › 2023 › 09 › 01 › weird-shell-arithmetic.gmi captured on 2024-06-16 at 12:49:11. Gemini links have been rewritten to link to archived content
⬅️ Previous capture (2023-11-14)
-=-=-=-=-=-=-
Portability might vary here; these assume ksh on OpenBSD 7.3.
$ FOO=42 ; echo $((FOO+1)) 43 $ FOO=42 ; echo $(($FOO+1)) 43
So what's the big deal?
$ FOO='42+9' $ echo $((FOO+1)) 52 $ echo $(($FOO+1)) 52
Okay maybe if you somehow get arithmetic operators into your supposed-to-be-numeric strings you get some unexpected math. But it's consistent, right?
$ FOO='1+2' $ echo $((FOO*2)) 6 $ echo $(($FOO*2)) 5
Whoops, that one had an order-of-operation issue.
$ FOO=0xa ; echo $((FOO-1)) ; echo $(($FOO-1)) 9 9 $ FOO=077 ; echo $((FOO-1)) ; echo $(($FOO-1)) 62 62
Octals and hexadecimal inputs will be acted on.
Probably the FOO='1+2' and similar forms are undefined behavior, and hopefully never show up unexpectedly in a shell script of yours that is trying to math. (I'd sooner switch to some other language.) `typeset -i` might force integer-ness on a variable, but then you have a case where weird input like '1+2' will be silently accepted. Others might prefer the script to blow up so someone can review where the bad input came from.
$ FOO=1+2 $ echo $((FOO*2)) $(($FOO*2)) 6 5 $ typeset -i FOO $ echo $((FOO*2)) $(($FOO*2)) 6 6
This is mostly a problem for scripts that process uncontrolled inputs that come from who knows where and contain who knows what and get handled as arithmetic. So probably pretty rare.
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_04
tags #unix #sh