调试脚本,-x 与设置-euxo pipelinefail 有什么区别?

调试脚本,-x 与设置-euxo pipelinefail 有什么区别?

我所知道的调试脚本的主要方法是添加-x到 shabang ( #!/bin/bash -x) 中。

我最近发现了一种新方法,set -euxo pipefail在 shabang 下添加,如下所示:

#!/bin/bash
set -euxo pipefail

这两种调试方式的主要区别是什么?有时您会更喜欢其中一种吗?

作为一名新生,读完这里后,我无法得出这样的结论。

答案1

首先,恐怕-o选项的解释由http://explainshell.com并不完全正确。

鉴于这set是一个内置命令,我们可以help通过执行以下命令查看其文档help set

  -o option-name
      Set the variable corresponding to option-name:
          allexport    same as -a
          braceexpand  same as -B
          emacs        use an emacs-style line editing interface
          errexit      same as -e
          errtrace     same as -E
          functrace    same as -T
          hashall      same as -h
          histexpand   same as -H
          history      enable command history
          ignoreeof    the shell will not exit upon reading EOF
          interactive-comments
                       allow comments to appear in interactive commands
          keyword      same as -k
          monitor      same as -m
          noclobber    same as -C
          noexec       same as -n
          noglob       same as -f
          nolog        currently accepted but ignored
          notify       same as -b
          nounset      same as -u
          onecmd       same as -t
          physical     same as -P
          pipefail     the return value of a pipeline is the status of
                       the last command to exit with a non-zero status,
                       or zero if no command exited with a non-zero status
          posix        change the behavior of bash where the default
                       operation differs from the Posix standard to
                       match the standard
          privileged   same as -p
          verbose      same as -v
          vi           use a vi-style line editing interface
          xtrace       same as -x

正如你所看到的-o pipefail意思:

管道的返回值是最后一个以非零状态退出的命令的状态,如果没有命令以非零状态退出,则返回零

但它没有说: Write the current settings of the options to standard output in an unspecified format.

现在,-x用于调试,正如您已经知道的那样,-e并将在脚本中出现第一个错误后停止执行。考虑这样的脚本:

#!/usr/bin/env bash

set -euxo pipefail
echo hi
non-existent-command
echo bye

该行在使用 echo bye时永远不会被执行,因为不返回 0:-enon-existent-command

+ echo hi
hi
+ non-existent-command
./setx.sh: line 5: non-existent-command: command not found

如果没有-e最后一行,就会被打印,因为即使发生错误,我们也没有告诉Bash自动退出:

+ echo hi
hi
+ non-existent-command
./setx.sh: line 5: non-existent-command: command not found
+ echo bye
bye

set -e通常放在脚本的顶部,以确保遇到第一个错误时脚本将停止 - 例如,如果下载文件失败,则提取它没有意义。

相关内容