“set -e -o pipefail”不适用于 Ubuntu 16 上的 bash 脚本

Dav*_*.it 11 command-line bash scripts

我一直在尝试在 Ubuntu 16 上运行我在 CentOS 7 上开发的 bash 脚本。

脚本的第一行是:

set -o nounset -o pipefail -o errexit
Run Code Online (Sandbox Code Playgroud)

当我尝试运行此脚本时,出现以下错误:

project.sh: 6: set: Illegal option -o pipefail
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题?我也在这个问题答案中解释了解决方案,但它没有帮助(我的文件不是make)。

Ser*_*nyy 16

在 Ubuntu 上,默认 shell 是dash(又名 Debian Almquist Shell),它/bin/sh是符号链接。当您的 shell 脚本使用 运行时#!/bin/sh,您实际上是在尝试使用默认 shell 运行它。但是,dash没有pipefail选项,这就是您收到错误的原因。

# Verifying what /bin/sh is symlinked to dash
$ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 2?  17  2016 /bin/sh -> dash
# Verify that pipefail doesn't exist as option for dash
$ dash    
$ set -o | grep pipefail                                              
$ set -o pipefail
dash: 1: set: Illegal option -o pipefail
$ sh
$ set -o pipefail
sh: 1: set: Illegal option -o pipefail
# Try this same option in bash
$ bash --posix
bash-4.3$ set -o pipefail
bash-4.3$  
# no error
Run Code Online (Sandbox Code Playgroud)

  • 只需命令“set -o”就会列出“set”支持的所有选项。 (2认同)