On Tue, Sep 1, 2015 at 12:50 PM, Greg Wooledge <wool...@eeg.ccf.org> wrote:

> On Tue, Sep 01, 2015 at 12:50:23AM -0400, Clint Hepner wrote:
> > Repeat-By:
> >
> >     foo=bar
> >     bar=5
> >     echo $(( foo ))    # produces 5
> >     echo $(( foo++ ))  # produces 5
> >     echo $foo          # produces 6, not bar
> >     echo $bar          # produces 5, not 6
>
> bar was never changed from its value of 5, so I would say the final
> result is correct.
>
> The $(( foo++ )) part is questionable.  You've asked bash to increment
> a variable (in a math context), but that variable doesn't have an
> integer value.  But it "points to" (contains the name of) a variable
> that does.
>
> I would say that any of the following would make sense:
>
>  1) An error message is printed.
>
>  2) foo is unchanged (still contains "bar"), and bar is incremented.
>
>  3) foo takes on the value of bar, and is then incremented.
>
> Bash happens to do #3.
>
> If you think of $(( foo++ )) as being basically equivalent to
> $(( tmp=foo, foo=foo+1, tmp )) then #3 is actually quite sensible.
>
>
For comparison, ksh 93u+ and zsh 5.0.2 do the same as Bash.

The version of dash I have handy (0.5.7) has math support which IMHO is
broken:

$ foo=bar
$ bar=5
$ echo $foo
bar
$ echo $((foo))
dash: 4: Illegal number: bar
$ echo $(($foo))
5
$ echo $((bar))
5
$ echo $(($bar))
5

Note the inconsistency in support of omitting the inner dollar sign. Also
post increment produces an error and pre increment produces no error and no
action:

$ echo $(($foo++))
dash: 9: arithmetic expression: expecting primary: "bar++"
$ echo $(($bar++))
dash: 10: arithmetic expression: expecting primary: "5++"
$ echo $((++$foo))
5
$ echo $foo
bar
$ echo $bar
5
$ echo $((++$bar))
5
$ echo $bar
5



-- 
Visit serverfault.com to get your system administration questions answered.

Reply via email to