Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Check a value of a variable 2

Status
Not open for further replies.

Autosys

Programmer
Jun 1, 2004
90
GB
Hi,

I'm farely new to Unix and was wondering if you could tell me how to check that a variable $TEST has a value assigned to it?

Do I do something like:

if [ $TEST = "" ] then
$EXITVAL=100
exit $EXITVAL

or is there a better way? Your help will be very much appreciated!

S
 
Code:
if [ -z "$TEST" ]
then
  EXITVAL=100
fi
exit $EXITVAL

or
Code:
[[ -z "$TEST" ]] && EXITVAL=100
exit $EXITVAL
 
Hi Autosys,

Your script is syntactically wrong. The "if" command has to be closed with a "fi".
Using the Korn shell you can use the following command to check whether a variable is or is not assigned: [[...]].
If the expression in the brackets is true, you will get an exit status of zero, otherwise a non-zero exit status.

In your case you can use:

Code:
[[ -z $TEST ]] && print "Variable is not assigned" || print "Variable is assigned"

[[ -z $TEST ]] checks for a zero string. The following output from the print commands are depending on the exit status of the [[...]] expression.

HTH

mrjazz

 
In ksh you also have another option:
Code:
[ ${TEST:?} ]
If the variable is not set it will abort the script with an error.
 
Code:
if [[ -z "$TEST" ]]
will check if $TEST is unassigned or assigned an empty value.

If you really want to check that no value was assigned, even an empty one:
Code:
if [[ -z "${TEST+assigned}" ]]; then
   echo "TEST is unassigned"
fi

--------------------

Denis
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top