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

23 debugging shell-script

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

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

#!/bin/bash
set -euxo pipefail
Run Code Online (Sandbox Code Playgroud)

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

作为一个大一新生,读到这里,我无法得出这样的结论。

Ark*_*zyk 25

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

鉴于这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
Run Code Online (Sandbox Code Playgroud)

如您所见,-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
Run Code Online (Sandbox Code Playgroud)

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

+ echo hi
hi
+ non-existent-command
./setx.sh: line 5: non-existent-command: command not found
Run Code Online (Sandbox Code Playgroud)

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

+ echo hi
hi
+ non-existent-command
./setx.sh: line 5: non-existent-command: command not found
+ echo bye
bye
Run Code Online (Sandbox Code Playgroud)

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