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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to identify a unix environment variable if existing.

Status
Not open for further replies.

6656

Programmer
Nov 5, 2002
104
US
Hi, How to identify if a ksh environment variable has been created by export command in the script.
i.e., export abc=xyz
What is the way to identify if abc exist.
Thanks, Mike
 
How about using the env command:

env|grep abc > /dev/null && echo "abc exist"

Regards,


Ed
 
Thanks Ed, I'll test it later. Mike
 
Hi:

The more I think about this, to be safe:

env|grep "^abc=" > /dev/null && echo "abc exists"
 
either:

#!/bin/ksh

foo=""

if [ ! ${foo:-} ] ; then
echo "not set"
else
echo "set"
fi;


OR

#!/bin/ksh

#foo="bar"

if [ ! ${foo:?"$(date): foo ain't set - bailing out"} ] ; then
echo "not set"
else
echo "set"
fi;


vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Actually, the Korn shell has a whole set of variable expansion formats to deal with this issue. If you don't know if variable ABC is set, you can do the following.

If you just want to tell if it's set or not, the command...
[tt]
print ${ABC:+&quot;ABC has been set&quot;}
[/tt]
...will do that. If you want to check the opposite, the command...
[tt]
print ${ABC:-&quot;ABC has not been set&quot;}
[/tt]
...will print whatever ABC is set to if it is set and not null, or, whatever's after the &quot;[tt]:-[/tt]&quot; if not. This can be either a string or another variable.

In either of these, you can put either a string or a variable in the last half.

If you do this...
[tt]
print ${ABC:?}
[/tt]
...it will print the value ABC is set to, if it is set, or &quot;[tt]ksh: ABC: parameter null or not set[/tt]&quot; if it's not.

If you do this...
[tt]
print ${ABC:?&quot;Missing variable, terminating!&quot;}
[/tt]
...it will print the value ABC is set to, if it is set, or will print the string and Exit the script if it's not.

If you do this...
[tt]
print ${ABC:=&quot;Something&quot;}
[/tt]
...it will print the value ABC is set to, if it is set, or will assign the value that's after the &quot;[tt]:=[/tt]&quot; to ABC, then print it. This will either use a variable if set, or set it if it's not set.

Hope this helps.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top