Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an environment variable is either unset or set to the empty string?

I don't want to use tcsh, but unfortunately have no choice in this situation. So please no "use another shell" answers!

I'm currently trying to check that an environment variable is both set, and that it's set to something useful. So what I want to do is this:

if ($?HAPPYVAR && $HAPPYVAR != "") then
    ... blah...
else if ($?SADVAR && $SADVAR != "") then
    ... more blah ...
endif

The problem is that if $HAPPYVAR is unset, it will error out on the second half of the expression (because the environment variable replacement happens early). I could use nested ifs, but then I'd have problems getting my "else" to work correctly (I'd have to set another env var to say whether "...blah..." happened or not).

Anyone got any nice, neat solution to doing this?

like image 274
spookypeanut Avatar asked Nov 12 '12 12:11

spookypeanut


People also ask

How do I check if an environment variable is empty?

To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"

How do you check if an environment variable is set?

In the command window that opens, enter echo %VARIABLE%. Replace VARIABLE with the name of the environment variable you set earlier. For example, to check if MARI_CACHE is set, enter echo %MARI_CACHE%. If the variable is set, its value is displayed in the command window.

How do you know if a variable is unset?

The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.

Can environment variable empty string?

If an environment variable is defined but is empty, Serverless reports it as 'Value not found at "env" source'. The value is found, it's just that value happens to be an empty string.


1 Answers

There is probably a nicer way, but you can use eval to delay the execution:

if ($?HAPPYVAR && {eval 'test ! -z $HAPPYVAR'}) then
    ... blah...
else if ($?SADVAR && {eval 'test ! -z $SADVAR'}) then
    ... more blah ...
endif

This seems to work for your needs.

If test doesn't work or you, this will work too:

if ($?HAPPYVAR && { eval 'if ($HAPPYVAR == "") exit 1' }) then

Ah, csh.

like image 178
quornian Avatar answered Oct 09 '22 06:10

quornian