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")
If the condition is merely checking if a variable is set, there's 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".
if [ "$b" -eq 5 ]; then a="$c"; else a="$d"; fi
The cond && op1 || op2
expression suggested in other answers has an inherent bug: if op1
has a nonzero exit status, op2
silently becomes the result; the error will also not be caught in -e
mode. So, that expression is only safe to use if op1
can never fail (e.g., :
, true
if a builtin, or variable assignment without any operations that can fail (like division and OS calls)).
Note the ""
quotes. The first pair will prevent a syntax error if $b
is blank or has whitespace. Others will prevent translation of all whitespace into single spaces.
(( a = b==5 ? c : d )) # string + numeric