有这样的方法吗
int a = (b == 5) ? c : d;
使用Bash ?
有这样的方法吗
int a = (b == 5) ? c : d;
使用Bash ?
当前回答
(( a = b==5 ? c : d )) # string + numeric
其他回答
这里有另一个选项,你只需要指定你分配一次的变量,不管你分配的是字符串还是数字:
VARIABLE=`[ test ] && echo VALUE_A || echo VALUE_B`
只是一个想法。:)
[ $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)) ? c : d ))
在Shell Scripting中,我们可以使用以下三种方式用于三元运算符:
[ $numVar == numVal ] && resVar="Yop" || resVar="Nop"
Or
resVar=$([ $numVar == numVal ] && echo "Yop" || echo "Nop")
Or
(( numVar == numVal ? (resVar=1) : (resVar=0) ))
更新:使用以下准备运行的示例扩展字符串计算的答案。这是利用上面提到的第二种格式。
$ strVar='abc';resVar=$([[ $strVar == 'abc' ]] && echo "Yop" || echo "Nop");echo $resVar
Yop
$ strVar='aaa';resVar=$([[ $strVar == 'abc' ]] && echo "Yop" || echo "Nop");echo $resVar
Nop