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: local x=$(cmd) hides a failed command in a shell function

Shell
~/tips/tip-shell-local-assign-hides-exit

local out=$(false)

Declare and assign on separate lines so a failure inside $( ) is not lost.

This one looks harmless and quietly breaks error handling. In local out=$(curl ...), the exit code you get afterwards belongs to local, not to curl.

local, export, declare and readonly are commands, and they succeed as long as the variable could be created. The failure of the command substitution gets lost:

f() {
  local out=$(false)
  echo "status: $?"   # 0
}

Even set -e does not stop here, because from its point of view nothing failed. Split the declaration from the assignment and the real status comes through:

fetch() {
  local out
  out=$(curl -fsS https://example.com/status) || return 1
  echo "$out"
}

Now out=$(...) is a plain assignment, its status is the status of curl, and || return 1 or set -e can react to it.

I find it slightly ugly to need two lines, but ShellCheck warns about the one-line form (SC2155) for exactly this reason. The same goes for export PATH_TO=$(...) outside functions. When the value comes from something that cannot fail, like a plain string, one line is perfectly fine.

Further reading: ShellCheck SC2155, Bash manual: Bash Builtins (local)

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link