Exit Codes and Script Status Reporting
Demonstrates proper exit code handling, error checking, set options for fail-safe behavior, and custom exit codes for script error reporting.
Code
#!/usr/bin/env bash
set -euo pipefail
# Custom exit codes
E_SUCCESS=0
E_NO_ARGS=1
E_FILE_NOT_FOUND=2
E_PERMISSION=3
E_DEPENDENCY=4
# Check dependencies
check_dependency() {
if ! command -v "$1" &>/dev/null; then
echo "Error: $1 is required but not installed" >&2
exit "$E_DEPENDENCY"
fi
}
# Main function with error handling
main() {
local input_file="${1:-}"
if [[ -z "$input_file" ]]; then
echo "Usage: $0 <input-file>" >&2
exit "$E_NO_ARGS"
fi
if [[ ! -f "$input_file" ]]; then
echo "Error: File not found: $input_file" >&2
exit "$E_FILE_NOT_FOUND"
fi
if [[ ! -r "$input_file" ]]; then
echo "Error: Cannot read file: $input_file" >&2
exit "$E_PERMISSION"
fi
local output
if ! output=$(wc -l "$input_file" 2>&1); then
echo "Error processing file: $output" >&2
exit 1
fi
echo "$output"
exit "$E_SUCCESS"
}
# Check required tools
for tool in grep sort wc; do
check_dependency "$tool"
done
main "$@"How it works
Strict mode (set -euo pipefail) makes failures loud — an unset variable or a failing pipeline stage aborts the script instead of being swallowed.
The work is delegated to check_dependency and main, chained so each stage’s output feeds the next.
2 helper functions (check_dependency and main) keep the repeated logic out of the main flow.
The script leans on parameter expansion 1 time, using forms like ${var:-default} so defaults, trimming, and casing happen inside the shell with no external tool.
Putting it to use
The script self-documents: the help branch prints $0 <input-file>.
The core lines, annotated
if ! command -v "$1" &>/dev/null; then
echo "Error: $1 is required but not installed" >&2
if ! output=$(wc -l "$input_file" 2>&1); then
echo "Error processing file: $output" >&2
for tool in grep sort wc; do
check_dependency "$tool"
Interactive Tools for This Topic
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
- Which external commands does the script rely on?
- `check_dependency`, `main` must be available on the PATH environment variable; everything else is shell built-in syntax.
Report a problem with this exampleOpens a pre-filled issue on GitHub.