The ternary operator is a form of syntactic sugar for an in-line if/else statement. Many languages natively support the operator:
Bash does not have a native ternary operator. Instead, the same functionality can be achieved using:
[[ "$color" == "blue" ]] has an exit status of 0, so it evaluates the right expression of the
&& and echoes the blue emoji.
[[ "$color" == "blue" ]] expression would have a nonzero exit status, so it evaluates the next logical statement (
||) and echos the green emoji.
Saving to a variable
If the right-hand side of the
&& condition has a nonzero exit status, it will silently default to the or (
[[ cond ]] && op1 || op2 ➜
op2 will be selected if
Takeaway: Be mindful of the
op1 operation. Ensure it exits with a 0 status code, or you may receive a false negative.