tags:

views:

96

answers:

5

Is there a way to do something like this using Bash?

int a = (b == 5) ? c : d;

Thanks.

+4  A: 

ternary operator ? : is just short form of if/else

case "$b" in
 5) a=$c
 *) a=$d
esac

Or

 [[ $b = 5 ]] && a="$c" || a="$d"
ghostdog74
Yes, I was looking for something like this. Thanks.
En_t8
Note that the `=` operator tests for string equality, not numeric equality (i.e. `[[ 05 = 5 ]]` is false). If you want numeric comparison, use `-eq` instead.
Gordon Davisson
+1  A: 
[ $b == 5 ] && a=$c || a=$d

But watch out with this construct, as the part after the || is also executed when the part between && and || fails.

larsmans
A: 

Code:

a=$([ "$b" == 5 ] && echo "$c" || echo "$d")
Dair T'arg
A: 
(( a = b==5 ? c : d )) # string + numeric
dutCh
A: 
(ping -c1 localhost&>/dev/null) && { echo "true"; } || {  echo "false"; }
wibble