Register
It is currently Sat Oct 25, 2014 9:41 pm

ternary operator in bash ... ex: echo $(( 2 == 2 ? 2+3 : 4 )


All times are UTC - 6 hours


Post new topic Reply to topic  [ 4 posts ] 
Author Message
 PostPosted: Thu Nov 20, 2008 3:42 am   

Joined: Thu Nov 20, 2008 3:17 am
Posts: 4
hi
i need to use the ternary operator in bash ...
the variant used in the title works ,

$ echo $(( 2 == 2 ? 2+3 : 4 ))
5
$ echo $(( 3 == 2 ? 2+3 : 4 ))
4

but when i try to use strings it gives me this :

$ echo $(( 3 == 2 ? "aaa" : "bbb" ))
bash: 3 == 2 ? "aaa" : "aaa" : syntax error: operand expected (error token is ""aaa" : "aaa" ")

Thanks in advance!


Top
 Profile  
 PostPosted: Mon Nov 24, 2008 3:21 am   

Joined: Thu Nov 20, 2008 3:17 am
Posts: 4
at least a tiny little hint ... :)


Top
 Profile  
 PostPosted: Wed Nov 26, 2008 6:46 pm   

Joined: Wed Nov 26, 2008 6:41 pm
Posts: 1
I am no expert, but I believe whenever you use (( )) it triggers mathematical functions and strings can't be used.

Why not use if statements instead?


Top
 Profile  
 PostPosted: Thu Nov 27, 2008 2:50 am   

Joined: Thu Nov 20, 2008 3:17 am
Posts: 4
you are right, it does mathematical evaluation,
but i have put it as an example of what i have managed to make it work ...

i have used for now if-then but the code looks very ugly and hard to understand or maintain .

also there is another option:
`test expr && echo trueVariant || echo falseVariant` but , still the ternary operator would the most elegant way to write code in this case

also, someone else has asked this question on experts-exchange:
http://www.experts-exchange.com/OS/Linu ... 71721.html
but i don't have an account there ...
maybe someone has one can forward-answer me ...

Thanks in advance!


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 4 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: Google [Bot] and 10 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP