有这样的方法吗

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

使用Bash ?


当前回答

代码:

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

其他回答

在bash中还有一个非常相似但更简单的三元条件语句语法:

a=$(( b == 5 ? 123 : 321  ))

三元运算符?:是if/else的缩写形式

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

Or

 [[ $b = 5 ]] && a="$c" || a="$d"
[ $b == 5 ] && { a=$c; true; } || a=$d

这将避免在&&和||之间的代码失败时意外执行||之后的部分。

这样的方法怎么样:

# any your function
function check () {
    echo 'checking...';

    # Change the following to 'true' to emulate a successful execution.
    # Note: You can replace check function with any function you wish.
    # Be aware in linux false and true are funcitons themselves. see 'help false' for instance.
    false; 
}

# double check pattern
check && echo 'update' \
    || check || echo 'create'; 

看看条件语句是如何在RxJs中工作的(即过滤器管道)。 是的,从我的角度来看,这是代码复制,但更实用的方法。

代码:

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