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

女生的网名这么多〃 提交于 2019-12-21 12:40:23

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/13343392/how-to-check-if-an-environment-variable-is-either-unset-or-set-to-the-empty-stri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!