bash echo 在 grep 不返回任何内容后不起作用



我知道人们通常在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。

bashshell 通常会执行脚本中的下一行,即echo "abc"即使grep返回退出状态 1。但是,如果启用了set -e,则bash不会在脚本中执行更多行。

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.

您可以使用以下命令与grep一起echo

printf "%sn" "$(grep -o "abc" /home/testuser/myapp.log)"

引用
  • grep 手册页
  • 如何在 Unix shell 脚本中使用 echo 和 grep?

">下一行回声不起作用"是什么意思? 根本达不到echo吗? 它是否运行但产生非零退出代码? 还是您在输出上看到abc? 知道您的脚本不会为grep返回任何内容,并且对脚本的其余部分一无所知,我可以说脚本不会为grep命令输出任何stdoutabcstdout对于echo

最新更新