如何检查环境变量是未设置还是设置为空字符串? [英] How to check if an environment variable is either unset or set to the empty string?

查看:246
本文介绍了如何检查环境变量是未设置还是设置为空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不想使用tcsh,但是不幸的是在这种情况下没有选择。所以请不要使用另一个shell的答案!



我正在尝试检查一个环境变量是否设置,并且它被设置为有用的东西。那么我想做的就是这样:

  if($?HAPPYVAR&& $ HAPPYVAR!=) 
... blah ...
else if($?SADVAR&& $ SADVAR!=)然后
...更多blah ...
endif

问题是如果$ HAPPYVAR未设置,则会在表达式的下半部分出错(因为环境变量替换发生得很早)。我可以使用嵌套的ifs,但是当我的else正常工作时,我会遇到问题(我必须设置另一个env var来表示是否发生... blah ...)。 p>

任何人都有任何好的,整洁的解决方案来做到这一点?

解决方案

可能有一个更好的方法,但是可以使用eval来延迟执行:

  if($?HAPPYVAR&& {eval'test!-z $ HAPPYVAR'})然后
... blah ...
else if($?SADVAR&& {eval'test!-z $ SADVAR'})然后
...更多blah ...
endif

这似乎适合您的需要。



如果 test 不起作用,你也可以这样做:

  if($? ($ HAPPYVAR ==)退出1'})然后

啊,csh。


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?

解决方案

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.

这篇关于如何检查环境变量是未设置还是设置为空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆