Ternary operator (?:) in Bash Ternary operator (?:) in Bash bash bash

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".