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!

Evaluate first condition

Status
Not open for further replies.

stackdump

Technical User
Sep 21, 2004
278
GB
I have an env variable that may or may not be set, if it is set then I want to check the path it holds exists.

Now I could do...
if ($?MYVAR) then
if -e $MYVAR then
etc.
endif
endif

but it would be nice to do;
if ($?MYVAR) && (-e $MYVAR) DoSomething

but that does not work if the var does not exist since it evaluates both conditions.

Is there a way I can do this in one statement? So something like;
if $?MYVAR if (-e $MYVAR) DoSomething
 

Try:
Code:
[[ ! -z $MYVAR && -d $MYVAR ]] && echo DoSomething
[3eyes]


----------------------------------------------------------------------------
The person who says it can't be done should not interrupt the person doing it. -- Chinese proverb
 
Nice idea, same problem though, it evaluates both conditions.
 
I disagree, when AND logic is involved it will stop evaluating the statement when the first FALSE is encountered.

However one improvement I would recommend is surrounding the variables in " quotes to prevent syntax errors when the variable is not defined (this may or may not be necessary depending on your shell, but is safer), and also the negative logic is not necessary, e.g.

Code:
[[ -n "$MYVAR" && -d "$MYVAR" ]] && echo "$MYVAR is defined and is a directory"

Annihilannic.
 
That doesnt work either, it complains that MYVAR is not defined. I think the problem is not the && but that the shell expects all variables in the statement to exist, before evaluating the function. This is the same reason that a line like;

if ($?MYVAR) echo $MYVAR

does not work. It will work if its done as;

if ($?MYVAR) then
echo $MYVAR
endif
 
And this ?
Code:
set +u
[ -n "$MYVAR" -a -d "$MYVAR" ] && echo "$MYVAR is defined and is a directory"

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
csh and oneliners IMHO aren't a good mix.

I'd stick to the multiline version as in OP.


HTH,

p5wizard
 


csh shell is obsolete, use ksh or bash or perl.
[noevil]




----------------------------------------------------------------------------
The person who says it can't be done should not interrupt the person doing it. -- Chinese proverb
 
I tried a ksh instead and get the same problem. "set +u" is not recognised.
 
Strange, what OS are you using? Seems to work on all of my kshs.

In any case you shouldn't need to do a set +u because it is normally the default in ksh (i.e. it doesn't complain about unset variables).

Did the rest of the code work okay for you under ksh?

Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top