有这样的方法吗
int a = (b == 5) ? c : d;
使用Bash ?
有这样的方法吗
int a = (b == 5) ? c : d;
使用Bash ?
当前回答
[ $b == 5 ] && { a=$c; true; } || a=$d
这将避免在&&和||之间的代码失败时意外执行||之后的部分。
其他回答
这和弗拉基米尔的回答很像。如果你的“三元”是一个“如果真,字符串,如果假,空”的情况下,那么你可以简单地做:
$ c="it was five"
$ b=3
$ a="$([[ $b -eq 5 ]] && echo "$c")"
$ echo $a
$ b=5
$ a="$([[ $b -eq 5 ]] && echo "$c")"
$ echo $a
it was five
(ping -c1 localhost&>/dev/null) && { echo "true"; } || { echo "false"; }
三元运算符?:是if/else的缩写形式
case "$b" in
5) a=$c ;;
*) a=$d ;;
esac
Or
[[ $b = 5 ]] && a="$c" || a="$d"
以下是一些选择:
在一行中使用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"`
[ $b == 5 ] && { a=$c; true; } || a=$d
这将避免在&&和||之间的代码失败时意外执行||之后的部分。