Discussion:
bash: checking if an env var is set?
(too old to reply)
Angel Tsankov
2006-10-19 14:35:27 UTC
Permalink
How do I check if an environment variable is set?
Chris
2006-10-19 14:39:27 UTC
Permalink
Angel Tsankov wrote:

[ follow-up set to c.o.l.misc as my nntp doesn't carry c.o.l.help ]
Post by Angel Tsankov
How do I check if an environment variable is set?
Use echo. e.g.

echo $PATH
Bit Twister
2006-10-19 15:01:43 UTC
Permalink
Post by Angel Tsankov
How do I check if an environment variable is set?
Well doing a
man test
would suggest you can test string for nonzero length or if length is zero.
Daniel Ganek
2006-10-19 15:25:53 UTC
Permalink
Post by Angel Tsankov
How do I check if an environment variable is set?
${foo+1}

If $foo is unset this expands to NULL
If $foo is set (including set to NULL) this will expand to 1

If NULL and unset are equivalent use ${foo:+1}

/dan
CBFalconer
2006-10-19 16:17:30 UTC
Permalink
Post by Angel Tsankov
How do I check if an environment variable is set?
If programatically, use getenv() in C. It returns NULL if not
found. From N869 (C standard):

7.20.4.5 The getenv function

Synopsis

[#1]

#include <stdlib.h>
char *getenv(const char *name);

Description

[#2] The getenv function searches an environment list,
provided by the host environment, for a string that matches
the string pointed to by name. The set of environment names
and the method for altering the environment list are
implementation-defined.

[#3] The implementation shall behave as if no library
function calls the getenv function.

Returns

[#4] The getenv function returns a pointer to a string
associated with the matched list member. The string pointed
to shall not be modified by the program, but may be
overwritten by a subsequent call to the getenv function. If
the specified name cannot be found, a null pointer is
returned.
--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>
Chris F.A. Johnson
2006-10-19 16:18:39 UTC
Permalink
Post by Angel Tsankov
How do I check if an environment variable is set?
[ -n "${VAR+x}" ] ## Fails if VAR is unset

[ -n "${VAR:+x}" ] ## Fails if VAR is unset or empty

[ -n "${VAR-x}" ] ## Succeeds if VAR is unset

[ -n "${VAR:-x}" ] ## Succeeds if VAR is unset or empty
--
Chris F.A. Johnson, author | <http://cfaj.freeshell.org>
Shell Scripting Recipes: | My code in this post, if any,
A Problem-Solution Approach | is released under the
2005, Apress | GNU General Public Licence
Feranija
2006-10-19 16:40:40 UTC
Permalink
Post by Angel Tsankov
How do I check if an environment variable is set?
echo $VARIABLE
Some Dude
2006-11-27 02:41:19 UTC
Permalink
Post by Angel Tsankov
How do I check if an environment variable is set?
shell:~$ env

That will list the environment variables.

Loading...