|
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: |
|
|
Output:
Exit code of 'true': 0 |
|
|
Failed command returns non-zero: |
|
|
Output:
Exit code of 'false': 1 |
|
|
Common exit codes by convention:
Check exit code with |
|
|
Output:
Found root user (grep returned 0) |
|
|
Using |
|
|
Output:
ls failed with exit code: 2 |
|
|
The |
|
|
Output:
run_check returned: 0 |
|
|
Return codes in functions use |
|
|
Output:
Check /etc/passwd: 0 Check /nonexistent: 1 |
|
|
Chain commands based on exit codes: |
|
|
Output:
Using && (run if previous succeeded): This runs because true succeeded Using || (run if previous failed): This runs because false failed |
|
|
Combine |
|
|
Output:
/tmp exists |
|
|
Exit codes with pipes - |
|
|
Output:
Pipe exit code: 1 |
|
|
Bash
Bash provides a |
|
|
Output:
First command: 1 Second command: Third command: |
|
|
Use |
|
|
Output:
Without set -e: This still runs With set -e: This runs |
|
|
Bash
Use This makes the script exit if any command in a pipeline fails, not just the last one. |
|
|
Custom exit codes for different error types: |
|
|
Output:
Invalid argument (code 1) |
|
|
Best practice: always check critical commands: |
|
|
Output:
Script completed successfully |
|