string - Shell 脚本三元运算符获取字符串结果

标签 string shell scripting ternary-operator

在 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 中不是有效的数字,并且 因此它的计算结果为0man 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/

相关文章:

javascript - Javascript 如何检查两个字符串是否包含相同的字符?

c++ - 函数如何检测字符串指针与字符串文字参数?

shell - 使用 mailx 和 uuencode 发送附件的 KornShell (ksh) 代码?

python - 如何避免在 Python 中对大量 dict 键字符串进行硬编码

java - 从 Android 中的 Google 翻译读取任何语言字符串

php - 从 PHP 调用的 shell 脚本问题

C fork() 导致未指定的意外函数调用

linux - Shell 脚本 - Linux - 列出空目录

c - 使用 C 语言制作具有 native 脚本支持的 Web 服务器

linux shell 脚本 : getting filename from a user input string