bash error handling - ghdrako/doc_snipets GitHub Wiki
Exit Codes
Exit codes are numeric values returned by commands or scripts upon completion.
- Convention: A zero exit code indicates success, while non-zero values denote errors
Exit with success
exit 0
Exit with an error
exit 1
Checking Command Exit Status
Use the $?
variable to check the exit status of the last command.
ls non_existent_file
if [ $? -ne 0 ]; then
echo "Error: File not found."
exit 1
fi
#!/bin/# Try to change to a directory
cd /some/nonexistent/directory
# Check the exit status of the last command
if [ $? -eq 0 ]; then
echo "Directory changed successfully."
else
echo "Failed to change directory."
fi
cd /some/path && echo "Success" || echo "Failure"
#!/bin/bash
# Function to handle errors
error_exit() {
echo "$1" 1>&2
exit 1
}
# Example usage
cp /source/file /destination/file || error_exit "Failed to copy file"
Conditional Execution
Use && and || operators for conditional execution based on the success or failure of commands.
# Execute the next command only if the previous one succeeds
command1 && command2
# Execute the next command only if the previous one fails
command1 || echo "Command1 failed."
Custom Exit Codes
Define custom exit codes for specific error scenarios to aid in identifying issues.
read_config_file() {
if [ ! -f "config.txt" ]; then
echo "Error: Configuration file 'config.txt' not found."
exit 2
fi
}
Implement error handling within functions using conditional statements or the set -e option to exit on errors.
Example:
divide() {
if [ $2 -eq 0 ]; then
echo "Error: Division by zero."
exit 1
fi
local result=$(( $1 / $2 ))
echo $result
}
result=$(divide 10 2)
echo "Result: $result"