[英]Why does “[[ '>' > '0' ]]” return false while “[ '>' \> '0' ]” returns true?
[英]Why ”false -a true“ and "true -a false" in shell return a different results?
IMO, -a
和&&
都是 shell 中and
操作,所以我假设true -a false
和false -a true
都会返回“false”。 那么事实是
[root@master ~] true -a false
[root@master ~] echo $?
0
[root@master ~] false -a true
[root@master ~] echo $?
1
[root@master ~] a=[ true -a false ]
[root@master ~] echo $a
true
[root@master ~] a=[ false -a true ]
[root@master ~] echo $a
true
为什么会发生这种情况,如果我想在壳牌中操作and
我应该怎么做?
让我们在 shell 中的命令的一般语法是:
[var=val...] cmd [args...]
var=val
在命令cmd
的持续时间内使用值val
导出环境变量var
。
为什么会发生这种情况
命令true
和false
都忽略参数。 true anything
以 0 退出状态退出, false anything
以非零退出状态退出。 true -a false
使用两个参数执行命令true
, sting -a
和 string false
。 true
忽略参数,以零退出状态退出。 相同的false
。
a=[
将值为字符串[
的变量a
导出到下一个命令的环境。
$ a=[ env | grep '^a='
a=[
a=[ true -a false ]
将环境变量a
设置为字符串[
的值,然后使用 3 个参数 string -a
、字符串false
和字符串]
执行命令true
。
a=[ true -a false ]
| | | | \---- third argument
| | | \---------- second argument
| | \------------- first argument
| \------------------ command to execute
\---------------------- var=val, exports a variable
true
忽略参数,再次为true
,退出状态0
。 false
也是如此,退出状态非零。
显示true
的值echo $a
是您之前在 shell 中设置的值。 a=[ true ...
仅在命令的持续时间内设置变量a
,之后变量具有自己的值。
$ a=anything_here
$ a=anything_here2 true anything_here3
$ echo $?
0 # true exits with 0 exit status
$ echo $a
anything_here # the variable `a` preserved its value set before the command
为什么shell中的“false -a true”和“true -a false”返回不同的结果?
因为命令false
和true
以不同的退出状态退出。
注意:字符串true
false
[
]
-a
对于 shell 没有特殊含义。 这些都是字符串。 当作为命令[
的参数传递时,字符串-a
和]
具有特殊含义。 它仍然是字符串-a
,但是当可执行文件[
被执行时,它会解析参数并专门作用于字符串-a
。 恰好有名为true
和false
的可执行文件。 字符串[
, ]
、 true
、 false
或-a
本身对 shell 没有意义,这些都只是字符串。
-a 和 && 都是和 shell 中的操作,
不, -a
是 shell 中的字符串-a
。 &&
是 shell 中的“与”操作。 -a
是[
或test
commands的“与”运算符。 注意:由于[
的问题,更喜欢使用[ ... ] && [ ... ]
而不是[ ... -a ... ]
。
参考: https ://pubs.opengroup.org/onlinepubs/9699919799.2018edition/utilities/test.html,https: //www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Simple-Command -扩展, https : //pubs.opengroup.org/onlinepubs/9699919799.2018edition/utilities/true.html,https : //pubs.opengroup.org/onlinepubs/9699919799.2018edition/utilities/false.html,https ://pubs .opengroup.org/onlinepubs/009604499/utilities/xcu_chap02.html#tag_02_09_01 。
感谢 KamilCuk 的回答。 读完之后,这是我的简短版本。
true -a false
和false -a true
只是一个包含两个参数的命令(-a [false/true])。 它的退出代码取决于分别返回 0 和 1 的命令本身。
a=[ true -a false
相同,但变量a
在执行true -a false
之前被设置为'['
。
如果未设置a
则应取消set -a
否则它将是'['
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.