bashsyntaxconditional-operator

Ternary operator (?:) in Bash


Is there a way to do something like this

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

using Bash?


Solution

  • The ternary operator ? : is just a short form of if/then/else:

    case "$b" in
     5) a=$c ;;
     *) a=$d ;;
    esac
    

    Or:

    [[ $b = 5 ]] && a="$c" || a="$d"