linux - 如何在设置了 -e 选项的 shell 中使用 grep

标签 linux bash shell

在 bash 中,-e 选项在出错后停止执行,并且 grep 命令返回非零状态,以防它找不到它正在寻找的模式。 我想在 if 语句中使用 grep,比如

#/bin/bash -e
if [[ `grep str /usr/lib/file.txt` -eq 0 ]]
  //do something
fi

如果我使用 $?获取最后一个命令的语句,然后执行在最后一个命令之后停止,因为 grep 返回非零状态。 必须有某种方法可以完成此操作,需要帮​​助找到它

最佳答案

就地做:

#/bin/bash -e
if grep -q str /usr/lib/file.txt; then
    echo "Found str"
else 
    echo "Didn't find str"
fi

注意 grep-q (--quiet) 选项,我们只对退出状态感兴趣。

关于linux - 如何在设置了 -e 选项的 shell 中使用 grep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41009627/

相关文章:

c++ - 错误 undefined reference `BP::Device::Create(std::string const&)'

linux - 删除目录中除列表中提到的文件之外的所有文件

bash - 如何判断 "find"命令的输出是否为空?

linux - AWK解释 awk -F'AUTO_INCREMENT =' ' NF==1{print "0";next}{sub(/.*/,"",$2);print $2}'

linux - 在 linux 邮件服务器上查找邮件消息

linux - 每秒 Ping 服务器以查看正常运行时间

bash - 如何从 unix 脚本发送电子邮件

c - 在我自己的 shell 中实现管道

linux - 如何使用命令的输出作为 linux 中其他程序的输入?

c - C 中带管道的 Shell 程序