Simon Branch <simonmbra...@gmail.com> wrote:
> In an arithmetic substitution -- that is, the $(( ... )) construct in a
> shell script -- one can reference variables either with ($a) or without
> (a) the dollar sign.  However, the latter is slightly better: the
> variable is interpreted as an integer, and then the integer is used
> inside the expression.  With the former, the variable's contents are
> spliced into the expression before it is parsed.  For example:
> 
>   $ a='1+5'
>   $ echo $((a * 2))
>   12
>   $ echo $(($a * 2))
>   11

[Speaking only about POSIX, not OpenBSD ksh and sh.]

https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_04

> If the shell variable x contains a value that forms a valid integer
> constant, optionally including a leading <plus-sign> or <hyphen-minus>,
> then the arithmetic expansions "$((x))" and "$(($x))" shall return the
> same value.

and before that

>  - Only the decimal-constant, octal-constant, and hexadecimal-constant
>    constants specified in the ISO C standard, Section 6.4.4.1 are
>    required to be recognized as constants.

Technically, your example is UB.

Then the description of OPTIND also makes no guarantees about whether
it can be used as $((OPTIND)) or not.

https://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html

> [...] the shell variable OPTIND shall be set to the index of the first
> operand, or the value "$#" +1 if there are no operands; [...]

That being said, consistency is always nice, and quite surely
$(($OPTIND - 1)) and $((OPTIND - 1)) behaves the same in most sane
usages.

-Lucas

Reply via email to