有这样的方法吗
int a = (b == 5) ? c : d;
使用Bash ?
有这样的方法吗
int a = (b == 5) ? c : d;
使用Bash ?
当前回答
这样的方法怎么样:
# 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中工作的(即过滤器管道)。 是的,从我的角度来看,这是代码复制,但更实用的方法。
其他回答
以下是一些选择:
在一行中使用if then else,这是可能的。
if [[ "$2" == "raiz" ]] || [[ "$2" == '.' ]]; then pasta=''; else pasta="$2"; fi
写一个这样的函数:
# Once upon a time, there was an 'iif' function in MS VB ...
function iif(){
# Echoes $2 if 1,banana,true,etc and $3 if false,null,0,''
case $1 in ''|false|FALSE|null|NULL|0) echo $3;;*) echo $2;;esac
}
像这样使用内部脚本
result=`iif "$expr" 'yes' 'no'`
# or even interpolating:
result=`iif "$expr" "positive" "negative, because $1 is not true"`
3-在案例回答的启发下,更灵活的一行用法是:
case "$expr" in ''|false|FALSE|null|NULL|0) echo "no...$expr";;*) echo "yep $expr";;esac
# Expression can be something like:
expr=`expr "$var1" '>' "$var2"`
这是通解
也适用于字符串测试 感觉更像是一种表达 避免在条件失效时产生任何微妙的副作用
数值比较试验
a=$(if [ "$b" -eq 5 ]; then echo "$c"; else echo "$d"; fi)
字符串比较测试
a=$(if [ "$b" = "5" ]; then echo "$c"; else echo "$d"; fi)
在bash中还有一个非常相似但更简单的三元条件语句语法:
a=$(( b == 5 ? 123 : 321 ))
回答:int a = (b == 5) ?C: d;
只写:
b=5
c=1
d=2
let a="(b==5)?c:d"
echo $a # 1
b=6;
c=1;
d=2;
let a="(b==5)?c:d"
echo $a # 2
记住" expression "等价于$((expression))
如果条件仅仅是检查是否设置了变量,甚至还有更短的形式:
a=${VAR:-20}
如果VAR已设置,则会将VAR值赋给a,否则将为其赋值默认值20——这也可以是表达式的结果。
这种方法在技术上称为“参数展开”。