how.wtf

Ternary operator in Bash

ยท Thomas Taylor

The ternary operator is a form of syntactic sugar for an in-line if/else statement. Many languages natively support the operator:

JavaScript:

1const color = 'blue';
2console.log(color === 'blue' ? '๐ŸŸฆ' : '๐ŸŸฉ');
3// Output: ๐ŸŸฆ

Python:

1color = "blue"
2print("๐ŸŸฆ" if color == "blue" else "๐ŸŸฉ")
3# Output: ๐ŸŸฆ

C:

1#include <stdio.h>
2#include <string.h>
3
4int main()
5{
6    char color[4] = "blue";
7    printf("%s", (strcmp(color, "blue") == 0) ? "๐ŸŸฆ" : "๐ŸŸฉ");
8}
9// Output: ๐ŸŸฆ

Ternary Operation

Bash does not have a native ternary operator. Instead, the same functionality can be achieved using:

1color="blue"
2[[ "$color" == "blue" ]] && echo "๐ŸŸฆ" || echo "๐ŸŸฉ"
3# Output: ๐ŸŸฆ

[[ "$color" == "blue" ]] has an exit status of 0, so it evaluates the right expression of the && and echoes the blue emoji.

Similarly, if color="green", the [[ "$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

1color="blue"
2emoji=$([[ "$color" == "blue" ]] && echo "๐ŸŸฆ" || echo "๐ŸŸฉ")
3echo $emoji
4# Output: ๐ŸŸฆ

โš ๏ธ Caution

If the right-hand side of the && condition has a nonzero exit status, it will silently default to the or (||) expression.

[[ cond ]] && op1 || op2 โžœ op2 will be selected if op1 fails.

Takeaway: Be mindful of the op1 operation. Ensure it exits with a 0 status code, or you may receive a false negative.

#bash  

Reply to this post by email โ†ช