为什么 && 使其左侧不会失败?

问题描述 投票:0回答:1

这个脚本:

#!/usr/bin/env bash

set -e

(
  set -e
  idontexist
  echo "launch the missiles"
) &&  echo "no errors"

打印:

line 7: idontexist: command not found
launch the missiles
no errors

使用 gnu bash 5.2。

这是为什么?

我假设

set -e
会导致
idontexist
线路失败,并且故障会冒泡。

bash shell
1个回答
0
投票

来自手册页:

              -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 sta‐
                      tus.   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 com‐
                      pound 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 applies to the shell  envi‐
                      ronment  and each subshell environment separately (see COMMAND EXECUTION ENVIRON‐
                      MENT 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  execut‐
                      ing in a context where -e is ignored, that setting will not have any effect until
                      the compound command or the command containing the function call completes.

特别是

如果复合命令或 shell 函数在 -e 所在的上下文中执行 被忽略,复合命令或函数中没有执行任何命令 即使设置了 -e 并且命令返回,主体也会受到 -e 设置的影响 失败状态。

© www.soinside.com 2019 - 2024. All rights reserved.