Coding/Learn/bash/bash exit codes
Bash Shell & CLI Automation Complete Course
01.What Bash Is & Shell Architecture
02.Terminal and Shell Basics
03.Running Commands & PATH Resolution
04.Command Structure: Options, Flags & Arguments
05.Getting Help with Commands: man, info & --help
06.Basic Filesystem Navigation & Directory Hierarchy
07.Listing Files with ls & Options
08.Changing Directories with cd
09.Current Directory: pwd & $PWD Variable
10.Creating Files: touch, Redirection & Here-Docs
11.Creating Directories with mkdir & Nested Parents
12.Copying Files and Directories with cp
13.Moving and Renaming Files with mv
14.Removing Files and Directories with rm & rmdir
15.Viewing File Contents: cat, less, more, head & tail
16.Command Aliases: alias, unalias & Persistence
17.Searching Text with grep & ripgrep
18.Pattern Matching: Regex & Extended Globs
19.Processing Columns & Structured Data with awk
20.Editing Text Streams with sed
21.Extracting Sections with cut, paste & tr
22.Sorting and Deduplication with sort & uniq
23.Viewing Beginning & End: head, tail & wc
24.Understanding Linux Processes & PID Lifecycle
25.Process Monitoring: top, htop & Background Jobs
26.Monitoring Disk Space with df
27.Directory Size Analysis with du & ncdu
28.Monitoring Memory Usage with free & /proc/meminfo
29.Terminating Processes: kill, killall, pkill & Signals
30.System Uptime, Load & Reboot History
31.Testing Connectivity: ping, nc, traceroute & nslookup
32.Making HTTP Requests with curl
33.Downloading Files with wget & curl -O
34.Remote SSH Connections: ssh, Keys & Config
35.Secure File Transfer with scp & sftp
36.File Synchronization with rsync
37.Creating and Managing ZIP Files
38.Extracting Archives: unzip & Safe Decompression
39.TAR Archives: Tape Archive Basics (tar -cvf, -tvf, -xvf)
40.Creating and Extracting Compressed Files (.tar.gz, .tar.bz2, .tar.xz)
41.Users and Groups: /etc/passwd, /etc/group & id
42.File Ownership: User Owner, Group Owner & Inodes
43.Read, Write & Execute Permissions: Files vs Directories
44.Changing Permissions with chmod: Symbolic & Octal Modes
45.Changing Ownership with chown
46.Changing Groups with chgrp & SetGID Inheritance
47.Script Structure & Strict Mode (set -euo pipefail)
48.The Shebang (#!) & Interpreter Portability
49.Variables: Declaration, Scope & Parameter Expansion
50.Data Types, Typeset & Declare Attributes
51.Operators: Arithmetic, String & Logical Operators
52.Handling User Input: read, Prompts & Secret Masking
53.Conditional Branching: if, elif, else & case Statements
54.Loops: for, while, until & Loop Control (break, continue)
55.Functions: Declarations, Local Scope & Return Values
56.Arrays: Indexed Arrays, Associative Maps & Slicing
57.Exit Codes ($?), Error Handling & Custom Exits
58.Scheduling with Cron & Crontab Automation
59.Combining Commands: Semicolons (;), &&, || & Subshells
60.Pipes (|), Pipefail & Process Pipelines
61.I/O Redirection: >, >>, 2>, 2>&1, &>, /dev/null & Here-Strings
62.Environment Variables: export, env, printenv & .env Loading
63.Command Substitution: $(command) vs Legacy Backticks
64.Basic Automation: Batch Processing & Lockfiles
65.Small Real-World Scripts: Health Checkers & Backup Utilities
66.Comprehensive Bash Exercises: Pipeline & Automation Challenges
67.Core Knowledge Quiz & Conceptual Review
68.Capstone Mini-Project: Automated Backup & Health Dispatcher
69.Course Completion & Verified Certificate
Course Certificate0%

Complete all lessons to earn

LearnExit Codes ($?), Error Handling & Custom Exits
57 / 69 0%
Lesson 57 of 69
5 mins read

Exit Codes ($?), Error Handling & Custom Exits

PreviousNext Lesson
In Plain English

Every command, binary, and script in Unix returns an integer Exit Status (Exit Code) between 0 and 255 upon termination. By universal standard, `0` signifies success, while any non-zero value (`1–255`) indicates an error or failure condition. The special parameter `$?` captures the exit code of the most recently executed command.

The Mental Model

"An exit code is like a doctor's report at the end of an examination: `0` is a clean bill of health; any number > 0 specifies the exact medical code for what went wrong."

Deep Dive: How It Works

Special Variable `$?`: Immediately stores the exit status of the previous foreground command.

Standard Conventions: `0` (Success), `1` (General error), `2` (Misuse of shell builtins), `126` (Command invoked cannot execute / permission denied), `127` (Command not found), `130` (Terminated by Ctrl+C / SIGINT 128+2).

The `exit` Command: `exit 0` ends the script with success; `exit 1` ends with error.

Syntax Blueprint

command
if [[ $? -ne 0 ]]; then
  echo "Command failed with code $?"
  exit 1
fi

# Or idiomatic short-circuit:
command || { echo "Failed"; exit 1; }

Inspect $? immediately after running a command or use short-circuit logic ||.

PointCore Rules to Remember

Point star
0 Means Success: Unlike boolean true/false in other languages, in Unix 0 is truthy (success).
Point star
$? is Overwritten Instantly: Every single command run rewrites $?. Save it into a local variable (`EXIT_CODE=$?`) if needed.
Point star
Custom Exit Codes: Define clear exit codes in your scripts (e.g. 2 for invalid args, 3 for network timeout).

Common Beginner Traps & How to Fix Them

Mistake:Running `echo $?` followed by `if [ $? -eq 0 ]`.

Why it happens: The `echo` command succeeds, resetting `$?` to 0 before the `if` statement can test it.

How to fix: Save `$?` to a variable immediately: `STATUS=$?; echo "Status: $STATUS"; if [ $STATUS -eq 0 ]...`.

Pro Tip: In Bash functions, return non-zero exit codes with `return 1` to indicate validation failure without killing the whole parent script.

Live Interactive Example

Hit Run Code to see it live
Capturing Exit Codes and Handling Failures
Git 2.45 / CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Output Console
Click "Run Code" to view the rendered output.
How it works: ls returned 0 (success) and grep returned 1 (no match found).

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Capture and Test an Exit Code

  • PointRun `true` (a command that always succeeds with 0).
  • PointCapture `$?` into `CODE=$?`.
  • PointEcho "Exit Code: $CODE".
1
2
3
4
5
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates