linux - bash echo 在 grep 什么都不返回后不起作用

标签 linux bash grep echo

我知道人们通常在 Linux 命令提示符(而不是脚本)中使用 grep。我碰巧将 grep 放在脚本中并遇到了一个奇怪的情况。如果 grep 命令没有返回任何内容,则下一行 echo 不起作用。下面是脚本。

grep "abc" /home/testuser/myapp.log
echo "abc"

这是 grep 的正常行为吗?如果是,为什么?

最佳答案

您的脚本中似乎启用了 set -e

通常,grep 的退出状态如果选择了一行则为 0,如果没有选择任何行则为 1,如果发生错误则为 2。但是请注意,如果使用 -q 或 --quiet 或 --silent 并选择了一行,即使发生错误,退出状态也是 0。在您的情况下,如果在 /home/testuser/myapp.log 中找不到 abcgrep 将返回 1。

bash shell 通常会执行脚本中的下一行,即 echo "abc" 即使 grep 返回退出状态1. 但是,如果启用 set -ebash 将不会再执行脚本中的任何行。

来自 bash 联机帮助页:

-e      Exit immediately if a pipeline (which may consist of a single simple command), a list, or  a  compound  command
        (see  SHELL GRAMMAR above), exits with a non-zero status.  The shell does not exit if the command that fails is
        part of the command list immediately following a while or until keyword, part of the test following the  if  or
        elif  reserved words, part of any command executed in a && or || list except the command following the final &&
        or ||, any command in a pipeline but the last, or if the command's return value is being inverted with !.  If a
        compound  command  other  than a subshell returns a non-zero status because a command failed while -e was being
        ignored, the shell does not exit.  A trap on ERR, if set, is executed before the shell exits.  This option  ap‐
        plies  to  the  shell  environment  and each subshell environment separately (see COMMAND EXECUTION ENVIRONMENT
        above), and may cause subshells to exit before executing all the commands in the subshell.
   
        If a compound command or shell function executes in a context where -e is being ignored, none of  the  commands
        executed within the compound command or function body will be affected by the -e setting, even if -e is set and
        a command returns a failure status.  If a compound command or shell function sets -e while executing in a  con‐
        text  where -e is ignored, that setting will not have any effect until the compound command or the command con‐
        taining the function call completes.

关于linux - bash echo 在 grep 什么都不返回后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70468619/

相关文章:

linux - bash shell 脚本 for 循环

Bash:使用文件名的一部分对查找结果进行排序

regex - 从html页面中提取数据的正则表达式

linux - 在文件列表中查找正则表达式

linux - 在 linux 中使用排序,如何在 2 之后生成 12?

linux - 错误 "/lib/x86_64-linux-gnu/libc.so.6: version ` GLIBC_2.3 3' not found"

c++ - Opencv2 示例程序不工作

linux - 多个awk在同一行打印

linux - 将 grep 搜索从多个文件粘贴到一个新文件

linux - 如何跟踪写入同一日志文件的多个线程