Exit Codes & Logical Chaining ($?, &&, ||)
Concept & Overview
Every command executed in Linux returns an exit status code between 0 and 255 upon completion:
- 0: Success (no errors occurred).
- 1-255: Failure or error code.
- The special shell parameter $? stores the exit code of the immediately preceding command: echo $?.
Shell logic operators chain commands based on exit codes:
- cmd1 && cmd2: Logical AND. Runs cmd2 only if cmd1 succeeds (exit code 0).
- cmd1 || cmd2: Logical OR. Runs cmd2 only if cmd1 fails (non-zero exit code).
Combining them creates clean resilient commands: mkdir backup && cp app.db backup/ || echo "Backup failed".
whoami followed by echo $?. Next, use conditional chaining to ensure the directory exists before copying: run mkdir backup && cp app.db backup/ || echo 'Backup failed'.Command Syntax Reference
| Command / Syntax | Description |
|---|---|
echo $? | Print exit code of the last command |
mkdir backup && cp app.db backup/ || echo 'Backup failed' | Conditionally create directory, copy file, or report failure |
Verification Objectives
These conditions will be automatically verified when you run commands inside the interactive terminal simulator:
- ○Inspect last exit code with "echo $?"
- ○Chain backup with "mkdir backup && cp app.db backup/ || echo 'Backup failed'"
- ○Verify app.db copied into backup/
Ready to complete Quest 104?
Test your skills live in the browser terminal with an emulated Linux filesystem, real-time command evaluation, and instant step-by-step hints.