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)

american-ninja-warrior
  • 7,397
  • 11
  • 46
  • 80
  • `set -e` is... *controversial* -- its behavior varies between shell releases and is often highly surprising. Consider reading [BashFAQ #105](http://mywiki.wooledge.org/BashFAQ/105). – Charles Duffy Mar 12 '17 at 18:11

2 Answers2

2

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
chepner
  • 497,756
  • 71
  • 530
  • 681
0

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
MaurGi
  • 1,698
  • 2
  • 18
  • 28