Operating System - HP-UX
1830178 Members
2241 Online
109999 Solutions
New Discussion

Re: How to evaluate a ?: operator from a shell script

 
Jdamian
Respected Contributor

How to evaluate a ?: operator from a shell script

I need to evaluate a expression like:
(A>B+1)?C+2:D
from a shell script without creating a shell function for parsing.

note: A, B, C and D are shell environment variables.

Can anyone help me ?
7 REPLIES 7
Steven Sim Kok Leong
Honored Contributor

Re: How to evaluate a ?: operator from a shell script

Hi,

Use the if-then-else construct:

#!/usr/bin/sh

if [ "$A" -gt "$B" ]
then
result=`expr $C + 2`
else
result="$D"
fi

Hope this helps. Regards.

Steven Sim Kok Leong
Steven Sim Kok Leong
Honored Contributor

Re: How to evaluate a ?: operator from a shell script

Hi,

Should be as follows:

#!/usr/bin/sh

temp=`expr $B + 1`
if [ "$A" -gt "$temp" ]
then
result=`expr $C + 2`
else
result="$D"
fi

Hope this helps. Regards.

Steven Sim Kok Leong
Peter Kloetgen
Esteemed Contributor

Re: How to evaluate a ?: operator from a shell script

Hi Damian,

Check out the following construction:

if [ "$A" -gt `expr $B + 1` ]
then
value=`expr $C + 2`
else
value="$D"
fi

Allways stay on the bright side of life!

Peter
I'm learning here as well as helping
Jdamian
Respected Contributor

Re: How to evaluate a ?: operator from a shell script

I see nobody understood me.

Supose user types the ?: expression, i.e., I don't know the expression in advance.

In the previous example, A, B, C and D are symbolic names for numerical values or environment variables. My script has no A, B, C or D variable names.
Steven Sim Kok Leong
Honored Contributor

Re: How to evaluate a ?: operator from a shell script

Hi,

Then you need to write a parser script language just for that, probably invent a new shell interpreter that does that. :)

Hope this helps. Regards.

Steven Sim Kok Leong
Wodisch
Honored Contributor

Re: How to evaluate a ?: operator from a shell script

Hi Damian,

the shell (well, at least Bourne, Korn, POSIX) does not have the C-style operator "?:"!
If you really need to use that operator, why not use a C-interpreter?
There do exist some OpenSource implementations...

Regards,
Wodisch
A. Clay Stephenson
Acclaimed Contributor

Re: How to evaluate a ?: operator from a shell script

Let me give you a plan B. Perl does have the ternary operator and if you use the eval function, the code is parsed and executed 'on the fly'.
If it ain't broke, I can fix that.