gunk-dev/the-valley

fail-nth.sh

sourceca98fdc29fbfmain's published tip history
1.0 KiB
1# shellcheck shell=bash
2# A stand-in for one tool, linked first on PATH under that tool's name. It
3# passes every call through to the real tool, except that it can fail one
4# call on purpose, so a check can fail each call a program makes in turn
5# and watch what the program does with the failure.
6#
7# SHIM_REAL_PATH the PATH to find the real tool on
8# SHIM_TOOL the tool whose calls are counted; others pass through
9# SHIM_COUNT a file holding the count of that tool's calls so far
10# SHIM_FAIL_AT the call to fail, counting from 1; 0 fails none
11# SHIM_STATUS the status the failed call exits with (default 2)
12tool="${0##*/}"
13real="$(PATH="$SHIM_REAL_PATH" command -v "$tool")" || {
14 echo "fail-nth: no real $tool on $SHIM_REAL_PATH" >&2
15 exit 127
16}
17if [ "${SHIM_TOOL:-}" = "$tool" ]; then
18 n=$(($(cat "$SHIM_COUNT") + 1))
19 echo "$n" > "$SHIM_COUNT"
20 if [ "$n" -eq "${SHIM_FAIL_AT:-0}" ]; then
21 echo "$tool: injected failure of call $n" >&2
22 exit "${SHIM_STATUS:-2}"
23 fi
24fi
25exec "$real" "$@"