[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: |
Stephane Chazelas |
Subject: |
Re: [Help-bash] How to tell if an environment variable exists or not |
Date: |
Wed, 7 Mar 2012 11:27:56 +0000 |
User-agent: |
Mutt/1.5.21 (2010-09-15) |
2012-03-06 14:31:59 -0700, Bob Proulx:
> Stephane Chazelas wrote:
> > Greg Wooledge wrote:
> > > Bill Gradwohl wrote:
> > > > Assuming set -u, how does one test to see if an environment
> > > > variable exists without creating it in the process?
> > >
> > > if [[ ${foo+defined} ]]
> > [...]
> >
> > Though that answer is probably what the OP was looking for,
> > please note that it will not differenciate between environment
> > variables and other shell variables.
> >
> > Also, this will only work for environment variables that can be
> > mapped to shell variables and are not masqued by builtin shell
> > variables (like *, 1...), some are being unexported or altered
> > by bash anyway.
>
> However programming a shell script with set -u in effect is
> problematic on a number of levels. This is just one of them. I think
> this is one of those features that sounds useful in theory and one
> that many people would ask to have available but then in practice
> turns out to be subtle and quick to anger. If it were a script I were
> writing or maintaining I would remove the set -u and rewrite it to
> work properly without it. In my experience that has been much less
> trouble in the long run. YMMV.
[...]
I totally agree. And I'd say the same goes for "set -e".
Both those flags also behave unexpectedly and non-portably in a
number of situations, like in subshells, nesting of compound
commands, functions...
Relying on those IMO is bad coding practice. In all languages,
you check for errors manually where it matters 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+.}\" ]"; }
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"
cmd || die # error message given by cmd
# exit code may mean false or error:
if grep -q foo /bar; then
echo found
else
[ "$?" -eq 1 ] || die # error
echo not found
fi
a=0
(( a++ )) # would exit with set -e
--
Stephane