有这样的方法吗
int a = (b == 5) ? c : d;
使用Bash ?
有这样的方法吗
int a = (b == 5) ? c : d;
使用Bash ?
当前回答
在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
其他回答
如果您想要类似的语法,您可以使用它
a=$(( $((b==5)) ? c : d ))
如果条件仅仅是检查是否设置了变量,甚至还有更短的形式:
a=${VAR:-20}
如果VAR已设置,则会将VAR值赋给a,否则将为其赋值默认值20——这也可以是表达式的结果。
这种方法在技术上称为“参数展开”。
三元运算符?:是if/else的缩写形式
case "$b" in
5) a=$c ;;
*) a=$d ;;
esac
Or
[[ $b = 5 ]] && a="$c" || a="$d"
这是通解
也适用于字符串测试 感觉更像是一种表达 避免在条件失效时产生任何微妙的副作用
数值比较试验
a=$(if [ "$b" -eq 5 ]; then echo "$c"; else echo "$d"; fi)
字符串比较测试
a=$(if [ "$b" = "5" ]; then echo "$c"; else echo "$d"; fi)
这样的方法怎么样:
# 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中工作的(即过滤器管道)。 是的,从我的角度来看,这是代码复制,但更实用的方法。