34

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.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
ramkrishna
  • 632
  • 1
  • 7
  • 24

3 Answers3

53

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

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

mklement0
  • 382,024
  • 64
  • 607
  • 775
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===
Community
  • 1
  • 1
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • The second part of this answer was an edit suggested by an anonymous user, which seems to be about variables masking environment variables with the same name. I'm not really sure that it is relevant to the question but I'm leaving it here in case it is useful to someone. – Tom Fenech Jun 21 '18 at 09:56
0

EDIT: see comment below.

if ( $?1 ) then
    echo "variable is empty"
else 
    echo "variable contains $1"
endif
DrGC
  • 168
  • 1
  • 5
  • 1
    You have the condition backwards. The behavior of `$?1` seems different from the behavior of `$?foo`; it appears that `$1` is always set, even if no corresponding argument was passed (which is why your solution works if you reverse the condition). `csh`, as opposed to `tcsh`, doesn't permit `$?1`. – Keith Thompson Jan 20 '17 at 16:58
  • oops, yes, you are right. Although i get the same also for tcsh, $?! always defined. – DrGC Jan 20 '17 at 18:33