unix
9 minShell Script Debugging: Trace Failures, Preserve Exit Codes, and Fix Safely
A root-cause workflow for shell failures involving quoting, pipelines, unset variables, traps, temporary files, and partial work.
Loading page...
unix
9 minA root-cause workflow for shell failures involving quoting, pipelines, unset variables, traps, temporary files, and partial work.
Q&A
Q&Agrep returns status 1 when there are no matches, which may trigger strict shell error handling.
grep commonly exits 0 when it finds a match, 1 when it finds none, and 2 for an error. With `set -e`, an expected no-match status can terminate a script unless handled intentionally. Distinguish absence from malformed input or permission failures rather than suppressing every status.
Q&A
Q&AWithout pipefail, a pipeline can appear successful even when one command in the middle failed.
When you pipe commands together, the shell normally reports the exit status of the last command. That hides failures earlier in the chain. Setting pipefail makes the pipeline fail if any stage fails, which is critical for build automation and production scripts where silent partial failures create huge operational risk.
Q&A
Q&ATrace selectively, preserve quoting and exit status, and avoid dumping sensitive expanded arguments.
Check the intended interpreter and run a syntax check first. Enable xtrace only around the suspect section because it prints expanded values; redirect diagnostics securely and mask credentials. Reproduce with controlled input, inspect each command status, and use ShellCheck to catch common quoting and portability issues.
Q&A
Q&AUse pipefail where supported and handle expected no-match statuses separately from actual errors.
Many shells report only the last pipeline command status. In Bash, `set -o pipefail` makes a pipeline fail when a stage fails. grep status 1 often means no match rather than a tool error, so scripts should distinguish that expected result from status 2 or an upstream failure.
Q&A
Q&AReplacing the shell with the service improves signal delivery and exit-code propagation.
Without exec, the shell can remain as the parent process and may not forward termination signals as intended. `exec service ...` replaces the shell, making the service the main process so it receives the container stop signal directly and its exit status is reported. A wrapper supervising multiple children must explicitly forward signals and reap them.
unix
8 minUnderstand users, groups, permission bits, file descriptors, and redirection so shell and service behavior is easier to debug.
unix
7 minFollow signals from a container stop through shell wrappers and child processes, and build shutdown behavior that preserves work.