brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: shopt -s inherit_errexit makes set -e work inside $( ) in bash

Bash
~/tips/tip-bash-inherit-errexit

set -e

Stop a command substitution at the first failing line, like the rest of the script.

With set -e on, a failing command inside $( ) does not stop the commands after it in that substitution. Bash turns set -e off in there, unless you ask it not to.

See the difference:

set -e
x=$(false; echo after)
echo "x=$x"          # x=after

false fails, but echo after still runs, the substitution succeeds and so does the script. Add the option and the substitution stops at false and fails, and then set -e ends the script:

set -e
shopt -s inherit_errexit
x=$(false; echo after)   # script exits here

For real code that means a function like get_config that runs a few commands inside $( ) now fails at the first broken one, instead of handing back half a result.

It needs bash 4.4 or newer. I’d put it in the header of new scripts together with set -euo pipefail. It does not fix every gap: the local x=$(...) problem stays, because there the exit code is thrown away by local itself, and commands inside an if condition still ignore set -e. Bash also turns the option on by itself in POSIX mode.

Further reading: Bash manual: The Shopt Builtin

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link