gpt4 book ai didi

bash - 为什么是 [[ ! ! expr ]] 等价于 [[ ! expr ]] 在 bash 中?

转载 作者:行者123 更新时间:2023-12-04 12:13:20 28 4
gpt4 key购买 nike

在 bash 中,我不明白为什么第三个命令不正确:

[[ 1 -eq 1 ]]         # $? is 0
[[ ! 1 -eq 1 ]] # $? is 1
[[ ! ! 1 -eq 1 ]] # $? is 1 (??)
[[ ! ( ! 1 -eq 1 ) ]] # $? is 0
如果我替换 1 -eq 1,它似乎会做同样的事情用任何真表达式,并用任何假表达式否定。

最佳答案

[[是一种扩展语法,提供(主要)[ 的超集.那么,要了解它的行为,应该从 [ 的标准开始。 .
The POSIX test specification描述如何[预期行为。在一个地方,它确实提供了符合此问题中描述的期望的描述:

! expression - True if expression is false. False if expression is true.


...但后来,关于如何根据原语数量进行解析的更详细描述与此预期相矛盾:
  • 0 arguments: Exit false (1).
  • 1 argument: Exit true (0) if $1 is not null; otherwise, exit false.
  • 2 arguments: If $1 is !, exit true if $2 is null, false if $2 is not null.If $1 is a unary primary, exit true if the unary test is true, false if the unary test is false.Otherwise, produce unspecified results.
  • 3 arguments: If $2 is a binary primary, perform the binary test of $1 and $3.If $1 is '!', negate the two-argument test of $2 and $3.(Obsolescent XSI behavior: If $1 is '(' and $3 is ')', perform the unary test of $2..On systems that do not support the XSI option, the results are unspecified if $1 is '(' and $3 is ')'.Otherwise, produce unspecified results.
  • 4 arguments: If $1 is '!', negate the three-argument test of $2, $3, and $4.(Obsolescent XSI behavior: If $1 is '(' and $4 is ')', perform the two-argument test of $2 and $3.)On systems that do not support the XSI option, the results are unspecified if $1 is '(' and $4 is ')'.Otherwise, the results are unspecified.
  • More than 4 arguments: The results are unspecified.

! ! 1 -eq 1的情况下,你有一个五参数的案例。 结果未明确 ,因为标准没有指定如果第一个参数是 !,五参数 case 是四参数 case 的否定。 .

正如 Zilog80 所建议的:如果您不想受到这些限制,请考虑放置您的 !在测试语法之外; ! [[ ... ]]发生在 shell 命令解析层而不是定制的测试语法特定逻辑中,和 ! ! [[ ... ]]在那里完全有效。

关于bash - 为什么是 [[ ! ! expr ]] 等价于 [[ ! expr ]] 在 bash 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67588425/

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