简体   繁体   中英

bash on ubuntu 16: set -e not inheriting inside subshell

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)

Command substitutions do not inherit the errexit option unless you are in POSIX mode or you use the inherit_errexit shell option (added to bash 4.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

This question. Worked on this for a couple of hours until I found htis.

I was not able to have set -e inherited to the subshells.

This is my proof of concept:

#!/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

execution without 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

execution with 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM