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!

Help with null variables

Status
Not open for further replies.

Wrathchild

Technical User
Aug 24, 2001
303
US
What's the best way to check to see if variables are Null? I have a script with approx. 9 variables and I would like to only use them in the commands if they are set. I played around with -n but it errored when the variable was null.
 
man test
A starting point:
[ -z "$varName" ] && echo varName not set

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 

Maybe you would like to assign default values if the variables are null:

Code:
VAR_NAME=${VAR_NAME:='DefaultValue'}
[3eyes]

----------------------------------------------------------------------------
The person who says it can't be done should not interrupt the person doing it. -- Chinese proverb
 
If you're testing for command line parameters, I usually do something like this...
Code:
#!/bin/ksh

VAR1=${1:-MISSING}

if [[ "${VAR1}" = "MISSING" ]]
then
    <do some stuff>
fi
It "reads" well so it's easy to debug or someone else to maintain.
 
ok, I have a variable called "test"
I made a script with the following:
Code:
if [ -z "$test" ]
then
rm filename
fi

I've set:
test=
test=""
test="asdf"

In all 3 situations the file gets removed...am I missing something?
 
It seems your script is executed in a subshell, and your variable test is not exported.
For example, if you define test=abc on your command line, and then you call your script, a new shell will be started, and the new shell will not know about this variable.
There are two possible solutions:

1) Define the varible test within the same script where you have if [ -z "$test" ]
- or -
2) Export the variable test to subshells:
export test=abc
(Syntax my differ, depending on your shell.)

hope this helps
 
including the variable in the script did the trick, thanks all!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top