加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

shell – 终端 – 为什么即使找不到匹配项,grep的exit命令也是0

发布时间:2020-12-15 21:00:41 所属栏目:安全 来源:网络整理
导读:我有这个命令: grep -E '^nothing' List.txt | echo $? 这里grep与任何东西都不匹配,我只是输出它的退出代码.根据grep的文档: Normally the exit status is 0 if a line is selected,1 if no lines were selected,and 2 if an error occurred. However,if
我有这个命令:

grep -E '^nothing' List.txt | echo $?

这里grep与任何东西都不匹配,我只是输出它的退出代码.根据grep的文档:

Normally the exit status is 0 if a line is selected,1 if no lines
were selected,and 2 if an error occurred. However,if the -q or
–quiet or –silent option is used and a line is selected,the exit status is 0 even if an error occurred. Other grep implementations may
exit with status greater than 2 on error.

但:

prompt:user$grep -E '^nothing' List.txt | echo $?
0
prompt:user$

但是,即使匹配不存在,为什么我得到0作为输出,我不应该得到预期的1退出代码吗?

解决方法

这就是问题:

grep -E '^nothing' List.txt | echo $?

通过使用单个|你正在发送grep的输出到echo,它总是打印上一个命令的退出状态,无论是否找到模式,它总是为0.

你可以使用grep -q:

grep -qE '^nothing' List.txt

按照男人的说法:

-q,--quiet,--silent
         Quiet mode: suppress normal output.  grep will only search a file until a match
         has been found,making searches potentially less expensive.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读