Robust error handling ensures your Bash scripts behave predictably when something goes wrong. This is especially important in automation, backups, and server management scripts.
Without error handling:
$?
)Every Bash command returns an exit code:
0
= successls /nonexistent
echo $? # 2 → Error
Use exit codes in conditions:
if [ $? -ne 0 ]; then
echo "Command failed"
fi
set
Options for Strict Error Checkingset -e
set -e
cp file.txt /protected/path/ # If fails, script stops
set -u
set -u
echo $username # Error if 'username' not set
set -o pipefail
set -o pipefail
grep "something" file.txt | sort | head
Without
pipefail
, only the last command’s exit code is checked.
trap
– Catch and Handle Errors or SignalsYou can trap signals like EXIT
, ERR
, INT
:
trap 'echo "An error occurred."' ERR
#!/bin/bash
set -e
cleanup() {
echo "Cleaning up temporary files..."
rm -f /tmp/tempfile
}
trap cleanup EXIT
touch /tmp/tempfile
cp /nonexistent /tmp/tempfile # Will trigger trap
Use command -v
to verify a tool exists before using it:
if ! command -v rsync &> /dev/null; then
echo "rsync not found. Please install it." >&2
exit 1
fi
||
Use ||
to run fallback logic:
mkdir /protected/dir || { echo "Failed to create dir"; exit 1; }
Tip | Reason |
---|---|
Use set -euo pipefail |
Makes script safer |
Use trap |
Ensure cleanup |
Check exit codes | Prevent silent failures |
Redirect stderr | command 2>error.log |
Quote your variables | Avoid word splitting |
#!/bin/bash
set -euo pipefail
trap 'echo "Something went wrong"; exit 1' ERR
backup_file="/tmp/backup.tar.gz"
echo "Starting backup..."
tar -czf "$backup_file" /important/data
echo "Backup completed at $backup_file"
set -x
trap
📁 File:
advance/error-handling.md
Author: Kashif Alam