如何在tcsh Shell中检查变量是否为空?

ram*_*hna 27 csh tcsh

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

if [ -z "$1" ] 
then
    echo "variable is empty"
else 
    echo "variable contains $1"
fi
Run Code Online (Sandbox Code Playgroud)

但我需要将其转换为tcsh shell.

mkl*_*nt0 35

关于使用tcsh/ cshapply 的标准警告,但这里是翻译:

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

但是请注意,如果您使用的是任意变量名而不是$1上面的名称,那么如果该变量尚未定义,则该语句将会中断(而$1始终定义,即使未设置).


为了计划变量(例如$var,可能没有定义)的情况,它变得棘手:

if (! $?var) then       
  echo "variable is undefined"
else
  if ("$var" == "")  then
      echo "variable is empty"
  else 
      echo "variable contains $var"
  endif
endif
Run Code Online (Sandbox Code Playgroud)

嵌套ifs的要求,以避免破坏脚本,因为tcsh显然不短路(一个else if分支的条件,即使将得到评估if进入分支;同样,两侧&&||表达式似乎总是评估-这至少适用尊重使用未定义的变量).