1

When I run this command

set -e; echo $(echo "$-");

I get himBH as the output. I was expecting the letter e to be included in the output. Whats going on?

I'm on Ubuntu 16.04.1 LTS with GNU bash, version 4.3.46(1)-release (x86_64-pc-linux-gnu)

4

2 回答 2

2

errexit除非您处于 POSIX 模式或使用inherit_errexitshell 选项(添加到bash4.4) ,否则命令替换不会继承该选项。

192% bash -ec 'echo "$(echo "$-")"'
hBc
192% bash --posix -ec 'echo "$(echo "$-")"'
ehBc
192% bash -O inherit_errexit -ec 'echo "$(echo "$-")"'  # 4.4+
ehBc
于 2017-03-12T17:52:51.417 回答
0

这个问题!为此工作了几个小时,直到我找到了 htis。

我无法set -e继承到子shell。

这是我的概念证明:

#!/usr/bin/env bash
set -euo pipefail

# uncomment to handle failures properly
# shopt -s inherit_errexit

function callfail() {
  echo "SHELLOPTS - callfail - $SHELLOPTS" >&2
  local value
  value=$(fail)
  echo "echo will reset the result to 0"
}

function fail() {
  echo "SHELLOPTS - fail     - $SHELLOPTS" >&2
  echo "failing" >&2
  return 1
}

function root() {
  local hello
  hello=$(callfail)
  echo "nothing went bad in callfail"
  callfail
  echo "nothing went bad in callfail"
}

root

没有执行shopt -s inherit_errexit

$ ./test.sh         
SHELLOPTS - callfail - braceexpand:hashall:interactive-comments:nounset:pipefail
SHELLOPTS - fail     - braceexpand:hashall:interactive-comments:nounset:pipefail
failing
nothing went bad in callfail
SHELLOPTS - callfail - braceexpand:errexit:hashall:interactive-comments:nounset:pipefail
SHELLOPTS - fail     - braceexpand:hashall:interactive-comments:nounset:pipefail
failing

执行shopt -s inherit_errexit

$ ./test.sh
SHELLOPTS - callfail - braceexpand:errexit:hashall:interactive-comments:nounset:pipefail
SHELLOPTS - fail     - braceexpand:errexit:hashall:interactive-comments:nounset:pipefail
failing
于 2021-06-21T21:11:08.620 回答