How can I check if a variable is empty or not in tcsh Shell?

好久不见. 提交于 2019-12-09 14:20:08

问题


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

But I need to convert it into tcsh shell.


回答1:


The standard warnings regarding use of tcsh/csh apply, 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

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).


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

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).




回答2:


You can try this (found here):

set name
if ( ${%name} == 0 ) then
        echo " Variable name has 0 characters as value."
endif

Note that the person who posted this has the following signature:

Standard advice: avoid csh family for scripting.

Note: This will break if name is an environment variable.

setenv name foobar ; set name ; echo '+++'$name'+++' ; unset name ; echo '==='$name'==='

++++++
===foobar===



回答3:


EDIT: see comment below.

if ( $?1 ) then
    echo "variable is empty"
else 
    echo "variable contains $1"
endif


来源:https://stackoverflow.com/questions/22640093/how-can-i-check-if-a-variable-is-empty-or-not-in-tcsh-shell

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