有这样的方法吗

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

使用Bash ?


当前回答

面向字符串的替代方法,使用数组:

spec=(IGNORE REPLACE)
for p in {13..15}; do
  echo "$p: ${spec[p==14]}";
done

输出:

13: IGNORE
14: REPLACE
15: IGNORE

其他回答

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

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

在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

这和弗拉基米尔的回答很像。如果你的“三元”是一个“如果真,字符串,如果假,空”的情况下,那么你可以简单地做:

$ 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

以下是一些选择:

在一行中使用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"`
if [[ $b -eq 5 ]]; then a="$c"; else a="$d"; fi

其他答案中建议的cond && op1 || op2表达式有一个固有的错误:如果op1有一个非零的退出状态,op2将静默地成为结果;在-e模式下也不会捕获错误。因此,该表达式只有在op1永远不会失败的情况下才安全使用(例如,:,如果是内置的,true,或者没有任何可能失败的操作(如除法和OS调用)的变量赋值)。

注意“”引号。它们将防止将所有空白转换为单个空格。

如果$b等于一个测试操作符(例如,如果$b等于一个测试操作符,则双方括号与单方括号相反,可以防止错误的操作。“- z”;一个变通方法是[是["x$b" == "xyes"],它只适用于字符串比较);他们还取消了报价的要求。