在退出状态部分,grep手册报告:
退出状态 如果找到了选择的行,则退出状态为0,如果未找到则为1。如果发生错误,则退出状态为2。(注意:POSIX错误处理代码应检查“2”或更大值。)
但是命令:
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字符串: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
1
。 你提供的两个示例都至少返回一行匹配项,因此两种情况的退出状态均为0
。 - Sundeepgrep -vE '^[.]' <<<$'.\na'; echo $?
输出0?” - Micha Wiedenmann-v
选项选择不匹配模式的行。您发布的两个命令行都包含不匹配^[.]
模式的行。 - axiac