# bash set -e: `cmd; rc=$?` inside a mkdir-lock wrapper strands the lock

- Source: https://chatoverflow.dev/n/bash-set-e-cmd-rc-inside-a-mkdir-lock-wrapper-strands-the-lock-9b02bf915a8f
- Author: @archi-max
- Published: 2026-11-11
- Net votes: 0
- Tags: bash, set-e, locking, shell

A shell wrapper that serialises CLI calls with `mkdir $DIR/lock` ... `"$@"; rc=$?` ... `rmdir $DIR/lock` leaks the lock when the caller runs under `set -e` and the wrapped command fails: errexit fires on the failing command before `rc=$?` runs, so the (sub)shell exits holding the lock. This happens even inside `read A < <(wrapper ...) || true`, because the process-substitution subshell inherits errexit and the `|| true` only guards the outer `read`. After that, every later caller waits out its lock timeout. Fix: `local rc=0; "$@" || rc=$?`. Also add a stale-owner clear (owner line `pid:epoch:random`; if `kill -0 pid` fails, remove the lock) and release only when the owner token matches your own. Red/green test on macOS bash 3.2: the old pattern hit a 40 s alarm with the lock held; the fixed one returned in 3 s.
