gpt4 book ai didi

grep - 'grep' 命令的退出状态码

转载 作者:行者123 更新时间:2023-12-04 16:03:40 30 4
gpt4 key购买 nike

grep退出状态部分报告中的手册:

EXIT STATUS       The  exit  status is 0 if selected lines are found, and 1 if not       found.  If an error occurred the exit status is 2.  (Note: POSIX       error handling code should check for '2' or greater.)

But the command:

echo ".
..
test.zip"|grep -vE '^[.]'
echo $?

echo "test.zip
test.txt"|grep -vE '^[.]'
echo $?
返回的值始终为 0。我期望 1 和 0。我做错了什么?

最佳答案

请记住 grep是基于线的。如果有任何行匹配,您就会匹配。 (在您的第一种情况下 test.zip 匹配(更准确地说:您与 -v 一起使用,因此您要求的行与您的模式不匹配,而 test.zip 正是这样做的,即与您的模式不匹配。结果您的 grep 调用成功了)。比较

$ grep -vE '^[.]' <<<$'.\na'; echo $?
a
0


$ grep -vE '^[.]' <<<$'.\n.'; echo $?
1

请注意第一个命令如何输出行 a ,也就是说它找到了匹配项,这就是退出状态为 0 的原因。将其与第二个示例进行比较,其中没有匹配的行。

引用文献
<<<是一个这里的字符串:
Here Strings
A variant of here documents, the format is:

[n]<<<word

The word undergoes brace expansion, tilde expansion, parameter and
variable expansion, command substitution, arithmetic expansion, and
quote removal. Pathname expansion and word splitting are not per-
formed. The result is supplied as a single string, with a newline
appended, to the command on its standard input (or file descriptor n if
n is specified).
   $ cat <<<'hello world'
hello world
$'1\na'用于获取多行输入( \n$'string' 内的换行符替换,更多信息参见 man bash )。
$ echo $'1\na'
1
a

关于grep - 'grep' 命令的退出状态码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49730043/

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