Operating System - HP-UX
1831311 Members
3538 Online
110023 Solutions
New Discussion

Re: How do I test to see if a variable is set in a script?

 
SOLVED
Go to solution
Rex Pommier
Frequent Advisor

How do I test to see if a variable is set in a script?

Hi. I have done some earchng of the forums and can't find the answer to this. Within a script, how do I check to see if a variable has been initialised?

TIA

Rex
5 REPLIES 5
Doug O'Leary
Honored Contributor
Solution

Re: How do I test to see if a variable is set in a script?

Hey;

You *should* be able to use the -z or -s switch to test to verify string length:

[[ -z "${var}" ]] && echo "string is zero length"
[[ -s "${var}" ]] && echo "String has a length"

I've had mixed results with that in the past, however. What I normally do is:

[[ "${var}x" = "x" ]] && echo "\${var} not set" || echo "\${var} is set"

HTH;

Doug

------
Senior UNIX Admin
O'Leary Computers Inc
linkedin: http://www.linkedin.com/dkoleary
Resume: http://www.olearycomputers.com/resume.html
James R. Ferguson
Acclaimed Contributor

Re: How do I test to see if a variable is set in a script?

Hi Rex:

I assume that you mean "in a shell script". If so, you can test with "-z". For instance:

#/usr/bin/sh
[ -z "${X}" ] && echo Empty!

...echo appropriately if the variable is empty.

Be sure to enclose the variable in double quotes to avoid syntatic failures at runtime.

Regards!

...JRF...
Rodney Hills
Honored Contributor

Re: How do I test to see if a variable is set in a script?

How about-

if set | grep -q "^x=" ; then echo "x has been initialized" ; fi

HTH

-- Rod Hills
There be dragons...
Rex Pommier
Frequent Advisor

Re: How do I test to see if a variable is set in a script?

Thanks for the responses. I was able to use them to get it working. Doug and James, I was able to use your suggestions, with the addition of wrapping them with a "set +u" and "set -u", otherwise I got the dreaded "parameter not set" error.

Rodney, I saw your suggestion and had one of those "duh" moments where I realised I was too busy looking for the trees to see the forest. Yours was the suggestion I decided to go with.

Thanks all for your quick responses.

Rex
Rex Pommier
Frequent Advisor

Re: How do I test to see if a variable is set in a script?

All the solutions worked for what I was trying to do.