syntax – Ternary operator (?:) in Bash
syntax – Ternary operator (?:) in Bash
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
Code:
a=$([ $b == 5 ] && echo $c || echo $d)
syntax – Ternary operator (?:) in Bash
If the condition is merely checking if a variable is set, theres even a shorter form:
a=${VAR:-20}
will assign to a
the value of VAR
if VAR
is set, otherwise it will assign it the default value 20
— this can also be a result of an expression.
This approach is technically called Parameter Expansion.