Bash-4.1 expression behavior change under "set -e"

Andrew Benton b3nton at gmail.com
Tue Jun 22 08:27:31 PDT 2010


On 22/06/10 14:49, linux fan wrote:
Interesting stuff
> A small test program verified the different behavior vs. earlier versions:
>
> #!/bin/bash
> # save as: fooey
> # usage: sh fooey [-e]

One little off topic nitpick. If your run a script with sh then sh will 
run the script and ignore lines beginning in#. If you want bash to run 
it use either ./fooey or bash fooey.
On my system sh is a symbolic link to dash so I get

andy:~$ sh fooey
[: 4: unexpected operator
fooey: 9: b: not found

bash fooey gives the output you've described


> [ "$1" == "-e" ]&&  set $1
> b=10
> while (( b>  -10 ));do
>    (( b = b - 1))
>    echo "$? $b"
> done
>
> The imaginary intent of the above test program was to print the
> decreasing numbers 9 through -10 preceeded by the exit code of setting
> the value. The imaginary unexpected result was the abrupt exit before
> printing the number zero.
>
> I guess the behavior change was so that they could write in the bash man page:
> ((expression)) ...  is exactly equivalent to let "expression"
>
> Replacing '(( b = b - 1))' with 'let b="$b - 1"' in the above performs
> identically in bash version 4.1.0 whereas in previous versions there
> was a variance.
>
> To replicate the old behavior, we have been afforded the opportunity
> to modify all code of that type so that it has an "or" branch which
> does nothing thusly:
> (( b = b - 1)) || :

Or instead of two lines:
   (( b = b - 1))
   echo "$? $b"

You could use one:
   echo "$? $((--b))"

>
> An alternative is to use the thing called "Arithmetic Expansion" that
> looks like $((expression)) and which does not trigger an exit when
> expression becomes zero in the "set -e" situation:
> b=$((b - 1))
>
> My little mind's logical concept of setting a variable to zero
> successfully is that it succeeded rather than failed.
>
> One line of code which I noticed failing was this line in jhalfs' progress bar:
> (( PREV_SEC = SEC ))
> The impact was that the progress bar abruptly exited for no apparent reason.
>
> Newer is better except always.
>
> FYI
Thanks for the info

Andy



More information about the lfs-support mailing list