gpt4 book ai didi

bash - 为什么 && 和 ||优于 -a 和 -o

转载 作者:行者123 更新时间:2023-11-29 09:08:54 26 4
gpt4 key购买 nike

在 bash 中编写 if block 时,shellcheck告诉我 &&|| 优于使用 -a-o

为什么?它更快,还是仅仅是一种让脚本看起来更简洁的风格偏好?

我得到的具体信息是:

^-- SC2166: Prefer [ p ] || [ q ] as [ p -o q ] is not well defined.

最佳答案

来自 the POSIX specification for test :

  • 4 arguments:

    The results are unspecified.

    [OB XSI] [Option Start] On XSI-conformant systems, combinations of primaries and operators shall be evaluated using the precedence and associativity rules described previously. In addition, the string comparison binary primaries '=' and "!=" shall have a higher precedence than any unary primary. [Option End]

因此:test 的使用有超过三个参数——如果你使用 -a-o,你重新依赖于 - 没有由未扩展的 POSIX 明确指定的行为。


现在,为什么会这样?因为在某些情况下,解析器可能会根据变量值做错事。

您还记得有人建议您做这样的事情吗?

if [ "x$foo" = "x$bar" ]; then ...

...这很愚蠢很古老,对吧?实际上,!考虑 foo=(bar=) 的情况,有人运行这样的命令:

if [ "$foo" -a "$bar" ]

扩展为以下内容:

if [ ( -a ) ]

...我们如何解析它?好吧,它可能是一个分组运算符(是的,test 在历史上被指定支持它们),检查-a 是否为非空;或者它可以检查 () 本身是否都是非空字符串;这是模棱两可的。这种歧义是 -a-o 不再是首选语法的原因。


那么,替代品是什么样子的?而不是:

[ "$foo" -gt "$bar" -a "$foo" -lt "$qux" ]

...你会这样写:

[ "$foo" -gt "$bar" ] && [ "$foo" -lt "$qux" ]

...关闭两个测试表达式并使用 shell 语法组合它们的输出。由于 [/test 是一个内置的 shell,它不需要作为外部命令执行,所以它不会有那种性能开销回到 70 年代,运行 test 意味着调用 /usr/bin/test

关于bash - 为什么 && 和 ||优于 -a 和 -o,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34755698/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com