help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] set -u in an arithmetic context


From: DJ Mills
Subject: Re: [Help-bash] set -u in an arithmetic context
Date: Wed, 25 Apr 2012 21:45:35 -0400

On Wed, Apr 25, 2012 at 7:57 PM, Bill Gradwohl <address@hidden> wrote:
> #!/bin/bash
>
> declare -a array
>
> set -u
>
> array[2]=5
>
> array[0]=$((array[1]-array[2]))
> echo A ${array[0]}
>
> array[3]=$((${array[4]}-${array[5]}))
> echo B ${array[3]}
>
> Produces:
> address@hidden # ./xxx
> A -5
> ./xxx: line 12: array[4]: unbound variable
>
>
> Can I conclude that because there is no ${} wrapper around the variables
> inside the arithmetic context in the first $(()) line that there is no
> parameter expansion going on and therefore the set -u does nothing?
>
> Is the output intended behavior or should set -u flag the line that works as
> an error?
>
> How does one get some form of protection during development if set -u
> doesn't work for the case I showed?
>
> --
> Bill Gradwohl
>

First of all, the best way to deal with this is to stop using set -u
and handle stuff yourself.

Second, expansions without $ or ${...} in an arithmetic are treated
specially. Unset or empty variables expand to 0. WITH the $, the shell
expands the variable before "((" or "$((" deals with it. Therefore,
set -u gets involved at that point. The arithmetic expressions will
also just see an empty value there, which could cause issues. Take
this simple example:

unset i
((! i)) && echo "yes"
yes

((! $i)) && echo "yes"
bash: ((: ! : syntax error: operand expected (error token is "! ")

In order to "fix" this, the order of parsing would have to be changed,
and a lot of other behavior would probably be affected. Again, the
best course of action, in my opinion, is simply to stop using set -u



reply via email to

[Prev in Thread] Current Thread [Next in Thread]