[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] How to tell if an environment variable exists or not
From: |
Stefano Lattarini |
Subject: |
Re: [Help-bash] How to tell if an environment variable exists or not |
Date: |
Wed, 07 Mar 2012 15:35:19 +0100 |
On 03/07/2012 12:27 PM, Stephane Chazelas wrote:
> 2012-03-06 14:31:59 -0700, Bob Proulx:
>>
>> However programming a shell script with set -u in effect is
>> problematic on a number of levels.
> [...]
>
> I totally agree.
>
I totally disagree :-) I use "set -u" in all my bash scripts (and several
POSIX sh script as well), and I've *never* had any problem with it -- only
bugs caught by it.
> And I'd say the same goes for "set -e".
>
This is quite true OTOH (Eric Blake listed the various issues with "set -e"
in a past thread on this list if I'm not mistaken); I use "set -e" only for
quick and simple hacks (where I'm too lazy to do proper error checking) or
for scripts part of a testsuite (where a spurious failure is just a minor
annoyance, and worth dealing with if that helps avoiding potentially
spurious successes).
> Both those flags also behave unexpectedly and non-portably in a
> number of situations, like in subshells, nesting of compound
> commands, functions...
>
True for "set -e"; I don't see how this can be a problem with "set -u".
> Relying on those IMO is bad coding practice. In all languages,
> you check for errors manually where it matters
>
But not for "programming" errors, like a typo in a variable name; the
interpreter/compiler is supposed to catch those, or at least help in
doing so (which is precisely what "set -u" does).
> or rely on a
> consistent exception raising/handling mechanism. Exit codes and
> set -e/-u can't be compared to such exception mechanism, It's
> far better to do it the C style.
>
> is_set() { eval "[ -n \"\${$1+.}\" ]"; }
>
(or even better IMHO: is_set() { [[ ${!1+set} == set ]]; }
> die() {
> [ "$#" -gt 0 ] && printf >&2 '%s\n' "$@"
> exit 1
> }
>
> debug=${DEBUG-0} # lower case shell variable initialised from
> # uppercase env var if provided
>
> is_set MYVAR || die "needed MYVAR not set"
>
But this won't catch typos like '$MYVRA' in the rest of the script
-- which is exactly what "set -u" aims at.
Regards,
Stefano