Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

csh

tcsh

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.

like image 901
ramkrishna Avatar asked Mar 25 '14 16:03

ramkrishna


People also ask

How do I check if a variable is empty in shell script?

To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"

Which shell is tcsh?

On Unix-like operating systems, tcsh (pronounced "tee-see-shell" or "tee-see-ess-aysh") is a command-line shell based on the C Shell. Its key features are programmable command completion and command-line editing.

How do I run tcsh in shell?

You can invoke the shell by typing an explicit tcsh command. A login shell can also be specified by invoking the shell with the -l option as the only argument. A login shell begins by executing commands from the system files /etc/csh. cshrc and /etc/csh.


2 Answers

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

like image 146
mklement0 Avatar answered Sep 22 '22 13:09

mklement0


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=== 
like image 29
Tom Fenech Avatar answered Sep 19 '22 13:09

Tom Fenech