Ternary operator in bash
Here’s a really quick tip for bash programmers.
In languages like C++, Java, Python, and the like, there’s the concept of a ternary operator. Basically it allows you to assign one value if a condition is true, else another.
In C/Java:
int x = valid ? 0 : 1;
In Python:
x = 0 if valid else 1
In Scala:
val x = if (valid) 0 else 1
Well, there’s no ternary operator in Bash, but there is a way to fake it.
valid=1 [ $valid ] && x=1 || x=0
Where whatever conditional you want is within the brackets.
If it’s valid, then the branch after the AND is followed, otherwise that after the OR is followed.
This is equivalent though perhaps a bit less readable then
if [ $valid ]; then x=1; else x=0; fi
So you should be aware of the construct in case you ever run into it, but it’s arguably less readable than just listing out explicitly what you’re doing.
Thanks to experts-exchange for making me aware of this little tip.
FYI:
echo $(( 1 == 1 ? 2 : 99 ))
works perfectly in Bash.
Good to know. Thanks.
however echo $(( 1 == 1 ? 2 : 99 )) will work only for numeric variable.
Smart! 😀
Great !! I t Works …
The equivalence of “if a; then b; else c; fi” and “a && b || c” is a fairly common misconception. The difference is that in the first case ‘a’ gets evaluated, and
depending on its return value _either_ ‘b’ _or_ ‘c’ gets evaluated, but not both.
In the second case, however, if ‘a’ has return value 0 (i.e. success/true), then
‘c’ can still be evaluated depending on the return value of ‘b’…
Is that true if it were (a && b) || c?
Yes, if a is true and b revaluates as false then c will be evaluated, which is nto the same as the if/then/else statement.
[ $valid ] && { x=$a; 1; } || { x=$b; }
Correction: [ $valid ] && { x=$a || 1; } || { x=$b; }