Bash Error Handling: A Practical Guide
cd command failed silently.The Default Trap
Consider this scenario:
#!/bin/bash
cd /some/directory/that/does/not/exist
rm important_file.txt
echo "Cleanup complete!"If the directory doesn't exist, the cd fails, but the script doesn't care. It proceeds to execute rm important_file.txt in whatever directory you are currently in. To stop this chaos, every script should include:
set -eThis ensures that if any command exits with a non-zero status, the script terminates immediately. It isn't a perfect solution with some edge cases, but it's a necessary survival mechanism for any real-world deployment.
The Pipeline Problem
Another critical flaw is how Bash handles pipelines. By default, it only checks the exit status of the very last command in a chain.
cat some_file.txt | grep "pattern" | sort | uniq > output.txtIf cat fails because the file is missing, the script ignores it as long as uniq succeeds. To fix this, use:
set -o pipefailNow, the pipeline's exit status is determined by the rightmost command that failed.
The "Golden Trio" of Bash Safety
For a robust AI workflow or any infrastructure script, I always use this combination at the top of the file:
set -euo pipefail- -e: Exit immediately on error.
- -u: (nounset) Exit if you reference an undefined variable. This prevents
rm -rf /$DIRECTORYfrom becomingrm -rf /due to a typo. - -o pipefail: Ensure pipeline failures are caught.
Moving from "hope-based" scripting to this strict configuration saved my team from several production mishaps during our initial LLM agent deployment. It turns a fragile sequence of commands into a predictable process.