|
|
|
Every command returns an exit code (0-255).
By convention, 0 means success and non-zero
indicates an error. The special variable |
|
|
Successful command returns 0: |
|
|
Failed command returns non-zero: |
|
|
Common exit codes by convention: 0 - Success 1 - General errors 2 - Misuse of shell command 126 - Command not executable 127 - Command not found 128+N - Fatal error signal N |
|
|
Check exit code with if statement: |
|
|
Using $? explicitly: |
|
|
The |
|
|
Return codes in functions use |
|
|
Chain commands based on exit codes: |
|
|
Combine && and || for simple conditionals: |
|
|
Exit codes with pipes - $? gives last command’s code: |
|
|
Bash
Bash provides PIPESTATUS array for all pipe exit codes: |
|
|
Use |
|
|
Use |
|
|
Bash
This makes the script exit if any command in a pipeline fails, not just the last one. |
|
|
Custom exit codes for different error types: |
|
|
Trap EXIT for cleanup regardless of exit code: |
|
|
Best practice: always check critical commands: |
|