在 shell 脚本中,我使用这样的三元运算符:
(( numVar == numVal ? (resVar=1) : (resVar=0) ))
我观看了 Derek Banas 的 shell 脚本教程,并在视频的 41:00 处得到了上述语法
https://www.youtube.com/watch?v=hwrnmQumtPw&t=73s
当我们将数字分配给 resVar
时,上面的代码有效,但如果我尝试将字符串分配给 resVar
,它总是返回 0。
(( numVar == numVal ? (resVar="Yop") : (resVar="Nop") ))
也尝试过
resVar=$(( numVar == numVal ? (echo "Yop") : (echo "Nop") ))
那么哪种方法是正确的呢?
最佳答案
您没有告诉我们您使用什么 shell,但您可能使用
bash
或类似的东西。 Bash
中的三元运算符仅适用于数字,如下所示
在 ARITHMETIC EVALUATION
部分下的 man bash
中进行了解释:
The shell allows arithmetic expressions to be evaluated, under certain circumstances (see the let and declare builtin commands and Arithmetic Expansion). Evaluation is done in fixed-width integers with no check for over- flow, though division by 0 is trapped and flagged as an error. The operators and their precedence, associativity, and values are the same as in the C language. The following list of operators is grouped into levels of equal-precedence operators. The levels are listed in order of decreasing precedence.
(...)expr?expr:expr
conditional operator
当您使用 "Yop"
或时 resVar
被分配 0
的原因
"Nop"
是因为这样的字符串在 bash
中不是有效的数字,并且
因此它的计算结果为0
。 man bash
中也对此进行了解释
同一段:
A null value evaluates to 0.
this Wikipedia article 中也对此进行了解释如果你找到它 更容易阅读:
A true ternary operator only exists for arithmetic expressions:
((result = condition ? value_if_true : value_if_false))
For strings there only exist workarounds, like e.g.:
result=$([ "$a" == "$b" ] && echo "value_if_true" || echo "value_if_false")
(where "$a" == "$b" can be any condition test, respective [, can evaluate.)
关于string - Shell 脚本三元运算符获取字符串结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48041845/