“grep”命令的退出状态代码

问题描述 投票:0回答:1

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

退出状态
       如果找到选定的行,则退出状态为 0,如果没有,则退出状态为 1
       成立。如果发生错误,退出状态为 2。(注意:POSIX
       错误处理代码应检查“2”或更大值。)

但是命令:

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

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

返回的值始终为 0。我本来期望的是 1 和 0。我做错了什么?

grep
1个回答
4
投票

请记住,

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
© www.soinside.com 2019 - 2024. All rights reserved.