Bash — Exit Codes
Exit codes
#!/bin/bash
# Success
exit 0
# Failure
exit 1
Checking exit codes
#!/bin/bash
ls /nonexistent 2>/dev/null
echo "Exit code: $?"
Common exit codes
| Code | Meaning |
|---|---|
| 0 | Success |
| 1 | General error |
| 2 | Misuse of shell command |
| 126 | Command not executable |
| 127 | Command not found |
| 128 | Invalid exit argument |
| 130 | Ctrl+C (SIGINT) |
| 255 | Exit status out of range |
Trap
#!/bin/bash
cleanup() {
echo "Cleaning up..."
rm -f /tmp/tempfile
}
trap cleanup EXIT
echo "Working..."
touch /tmp/tempfile
Mini Practice
Write Bash code that:
- Returns different exit codes
- Checks exit codes with
$? - Uses
trapfor cleanup
Up Next
In the next lesson, you'll learn about Input Output — reading and writing files.
Related Topics
Frequently Asked Questions about Exit Codes
What is Exit Codes in Bash?
Exit Codes is a fundamental concept in Bash. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Exit Codes?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Exit Codes.
Why is Exit Codes important in Bash?
Exit Codes is essential for Bash development. Understanding this concept will help you write better code and solve real-world problems more effectively.