Ternary operator (?:) in Bash

En_t8 picture En_t8 · Oct 17, 2010 · Viewed 248.9k times · Source

Is there a way to do something like this

int a = (b == 5) ? c : d;

using Bash?

Answer

ghostdog74 picture ghostdog74 · Oct 17, 2010

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"