如何在tcsh Shell中检查变量是否为空? [英] How can I check if a variable is empty or not in tcsh Shell?

查看:166
本文介绍了如何在tcsh Shell中检查变量是否为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我必须检查bash shell中变量是否为空,则可以使用以下脚本进行检查:

IF I have to check that if a variable is empty or not for that in bash shell i can check with the following script:

if [ -z "$1" ] 
then
    echo "variable is empty"
else 
    echo "variable contains $1"
fi

但是我需要将其转换为tcsh shell。

But I need to convert it into tcsh shell.

推荐答案

关于使用 tcsh / csh 的标准警告适用(不适用由于其固有的限制,因此将其用于脚本 ,但翻译如下:

The standard warnings regarding use of tcsh/csh apply (don't use it for scripting, due to its inherent limitations), but here's the translation:

if ( "$1" == "" ) then      # parentheses not strictly needed in this simple case
    echo "variable is empty"
else 
    echo "variable contains $1"
endif

但是请注意,如果要使用任意变量名而不是 $ 1 中,如果尚未定义该变量,则语句会中断(而 $ 1 始终是定义的,即使未设置也是如此)。

Note, though, that if you were to use an arbitrary variable name rather than $1 in the above, the statement would break if that variable weren't defined yet (whereas $1 is always defined, even if unset).

要计划变量的情况,例如 $ var ,可能未定义,这很棘手:

To plan for the case where a variable, say $var, may not be defined, it gets tricky:

if (! $?var) then       
  echo "variable is undefined"
else
  if ("$var" == "")  then
      echo "variable is empty"
  else 
      echo "variable contains $var"
  endif
endif

嵌套 if 是必需的,以避免破坏脚本,因为 tcsh 显然不会短路(如果分支的条件将被评估,即使输入 分支;同样,& || 表达式似乎总是被评估-至少在使用未定义变量时适用。)

The nested ifs are required to avoid breaking the script, as tcsh apparently doesn't short-circuit (an else if branch's conditional will get evaluated even if the if branch is entered; similarly, both sides of && and || expressions are seemingly always evaluated - this applies at least with respect to use of undefined variables).

这篇关于如何在tcsh Shell中检查变量是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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