We help IT Professionals succeed at work.

How to convert this statement to use the ternary operator ( ? : )

jrram
jrram asked
on
How can I convert the below shell script text snippet to use a ternary operator.  I read at http://safari.oreilly.com/0131478230/ch11lev1sec5 that Linux does support a ternary operator, but I'm having trouble figuring out how to do it.

I know if this was Javascript, I could do:

   EXISTS=(text=="Apple") ? "Passed" : "Failed";

But because of the quirky syntax of Linux, I'm not sure how to convert it.
text="Apple"
 
if [ $text = "Apple" ];
then
        EXISTS="Passed"
else
        EXISTS="Failed"
fi

Open in new window

Comment
Watch Question

Top Expert 2005
Commented:
in bash?

[ "$var" = "Apple" ] && EXISTS="Passed" || EXISTS="Failed"


BTW,
text="Apple"
if [ $text = "Apple" ];
always returns true, isn't it?

Commented:
Linux doesn't support any ternary operator, I think you mean the Bourne shell (/bin/bash)
to get consistent behavior, you need to know which shell you are using, so good shell scripting
design always starts by specifying which interpreter (/bin/sh, /bin/csh, /bin/ksh, /bin/bash, /bin/tcsh, /bin/perl)
to use.


And ravenol's solution is correct

#!/bin/sh
 
# Rest if script follows...

Open in new window

Author

Commented:
Yes, it will always be true...that was a bad example.... but your solution worked.

Its a little different since you have to use the EXISTS= statement twice.  But it works.

Author

Commented:
I'm using the Bash shell.