bashGuardPrelude function

String bashGuardPrelude()

The guard prelude prepended to every bash tool script (POSIX):

  • set -- restores sh -c positional-parameter parity ($# = 0, empty "$@") — the . "$1" delivery otherwise leaves the script path as $1.
  • kill() filters bashGuardPidsEnv pids (and their non-leading -pgid group targets — a leading -<number> is the kill grammar's signal number, not a target) out of the arguments before invoking the real kill. No protected hit → the call is passed through byte-identical. Every construct is set -e/set -u-safe (if-chains, guarded expansions).

Implementation

String bashGuardPrelude() =>
    '''
# ── fa bash-guard (gh-1763): self-defense prelude ──────────────────────
# Restore sh -c positional-parameter parity, then keep kill() from
# signaling the harness/ancestor pids exported via $bashGuardPidsEnv.
set --
kill() {
  __fa_rest=''
  __fa_pids_left=0
  __fa_hit=0
  __fa_pos=0
  for __fa_a in "\$@"; do
    case "\$__fa_a" in
      ''|-|--|%*|-[A-Za-z]*)
        __fa_rest="\$__fa_rest \$__fa_a"
        ;;
      -[0-9]*)
        __fa_n="\${__fa_a#-}"
        if [ "\$__fa_pos" -eq 0 ]; then
          # kill grammar: a LEADING -<number> is the SIGNAL NUMBER (kill
          # -9 <pid>), not a target — pass it through uncounted.
          __fa_rest="\$__fa_rest \$__fa_a"
        else
          # After another arg (or --) -<number> is a process-group target
          # (kill -- -<pgid>): same keep/hit/count treatment as a
          # positive pid.
          __fa_keep=1
          for __fa_p in \${$bashGuardPidsEnv:-}; do
            if [ "\$__fa_n" = "\$__fa_p" ]; then __fa_keep=0; break; fi
          done
          if [ "\$__fa_keep" = 1 ]; then
            __fa_rest="\$__fa_rest \$__fa_a"
            __fa_pids_left=\$((__fa_pids_left + 1))
          else
            __fa_hit=1
          fi
        fi
        ;;
      *)
        __fa_keep=1
        for __fa_p in \${$bashGuardPidsEnv:-}; do
          if [ "\$__fa_a" = "\$__fa_p" ]; then __fa_keep=0; break; fi
        done
        if [ "\$__fa_keep" = 1 ]; then
          __fa_rest="\$__fa_rest \$__fa_a"
          __fa_pids_left=\$((__fa_pids_left + 1))
        else
          __fa_hit=1
        fi
        ;;
    esac
    __fa_pos=\$((__fa_pos + 1))
  done
  if [ "\$__fa_hit" = 0 ]; then
    command kill "\$@"
    return
  fi
  __fa_rc=0
  if [ "\$__fa_pids_left" -gt 0 ]; then
    # shellcheck disable=SC2086 — every surviving arg is a single word.
    command kill \$__fa_rest || __fa_rc=\$?
  fi
  echo 'fa: kill skipped protected pid(s) (gh-1763 bash-guard)' >&2
  return "\$__fa_rc"
}
''';