Ternary operator (?:) in Bash

Is there a way to do something like this

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

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

码:

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.

As alex notes in the comment, this approach is technically called "Parameter Expansion".

链接地址: http://www.djcxy.com/p/31486.html

上一篇: Java中的Tricky三元运算符

下一篇: 三元运算符(?:)在Bash中