Bash exec File-Descriptor Redirection Logging Prompt
Wire script-wide logging with exec, custom file descriptors, and tee to split stdout/stderr to console and log files
- Target user
- Senior DevOps engineers and SREs building production shell automation
- Difficulty
- Advanced
- Tools
- Claude, ChatGPT, Cursor
The prompt
You are a senior Bash engineer adding production-grade logging to a script using `exec` and custom file descriptors. Wire script-wide stdout/stderr capture without sprinkling `>> logfile` on every command. 1. At the top of the script (after strict mode), save the original terminal streams to spare descriptors so the console is recoverable: `exec 3>&1 4>&2`. Explain why preserving the originals matters before redirecting. 2. Redirect all subsequent stdout and stderr through `tee` to a log file while still showing them live: use `exec > >(tee -a "[LOG_FILE]") 2> >(tee -a "[LOG_FILE]" >&2)` so the script body needs no per-command redirection. 3. Keep stdout and stderr distinguishable in the log: prefix or color stderr (e.g. via a `log()`/`err()` helper that timestamps each line) so a reader can tell error lines from normal output even though both land in one file. 4. Add a `trap` on `EXIT` that flushes and restores the saved descriptors (`exec 1>&3 2>&4; exec 3>&- 4>&-`), then waits on the `tee` process-substitution children so no log lines are lost when the script exits. 5. Make the log target configurable via `[LOG_FILE]` with a sane default under `[LOG_DIR]`, create the directory with `mkdir -p`, and `chmod` it to `[FILE_MODE]` if the log may contain sensitive output. 6. Show an optional second descriptor (`exec 5>>"[AUDIT_FILE]"`) for a structured audit stream that the script writes to explicitly with `>&5`, separate from the human log. Output format: return (a) the complete logging-enabled script in one fenced ```bash block, (b) an ASCII diagram of which fd points where before and after the exec redirections, and (c) the exact teardown sequence in the EXIT trap. Guardrail: the logging setup must be idempotent and append-only — re-sourcing or re-running it must never truncate an existing log, must leave fds 0/1/2 restored to their originals on exit (success or failure), and must not leak descriptors 3/4/5 to child processes.
Why this prompt works
Scripts usually grow logging by appending >> logfile 2>&1 to individual commands, which is fragile, easy to forget, and impossible to keep consistent. The professional approach is to redirect the script’s own stdout and stderr once, at the top, with exec, so every command thereafter is captured automatically. This prompt teaches that pattern correctly: it first saves the original terminal streams to spare descriptors (exec 3>&1 4>&2) so the console is recoverable, then routes everything through tee so output is both displayed live and persisted — the behavior operators actually want, rather than choosing between a silent script and a screen-only one.
The hard parts of fd-based logging are the ones beginners skip, and the prompt forces all of them. tee lives inside a process substitution, which means it is an asynchronous child; if the script exits before that child flushes, the last lines of the log are lost — a maddening, intermittent bug. By requiring an EXIT trap that restores fds 1/2 to their saved originals and then waits on the tee children, the prompt guarantees a clean, complete log on every exit path including failure. Keeping stderr visually distinct in a merged log, and offering a dedicated audit descriptor (exec 5>>), reflects how real incident reviews read these files: you need to separate errors and machine-auditable events from ordinary chatter.
The output requirements — a full script, an fd-mapping diagram, and the exact teardown order — make an inherently subtle topic legible to a reviewer, while the append-only, no-leak, fds-restored guardrail keeps the logging layer from ever clobbering history or leaking descriptors into child processes. The result is a logging harness you can paste atop any automation script and trust under both success and failure.
Related prompts
-
Bash Leveled Logging Library Prompt
Build a small, sourceable Bash logging library with DEBUG/INFO/WARN/ERROR levels, timestamps, TTY-aware color, and a LOG_LEVEL threshold — so your scripts emit consistent, greppable output to stderr.
-
Bash Process Substitution Patterns Prompt
Use process substitution to feed command output where a filename is expected — diffing two live command outputs, tee-ing to multiple consumers, and avoiding subshell variable loss
-
Bash Script Code Review Prompt
Get a senior-engineer review of any Bash script — safety, idempotency, error handling, portability.