</>
Skip to content
Bash lessons (17/29)

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

CodeMeaning
0Success
1General error
2Misuse of shell command
126Command not executable
127Command not found
128Invalid exit argument
130Ctrl+C (SIGINT)
255Exit 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:

  1. Returns different exit codes
  2. Checks exit codes with $?
  3. Uses trap for 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.