Exit statuses are numerical codes returned by commands or scripts in a Unix-like operating system, indicating the success or failure of the command's execution. Here's how they work:
Basic Concepts
-
Exit Status Code:
- Every command returns an exit status code when it finishes executing.
- By convention, an exit status of
0indicates success, while any non-zero value indicates an error or failure.
-
Checking Exit Status:
- You can check the exit status of the last executed command using the special variable
$?. - For example:
command echo $? - This will print the exit status of
command.
- You can check the exit status of the last executed command using the special variable
Common Exit Status Codes
0: Success1: General error (catch-all for miscellaneous errors)2: Misuse of shell builtins (e.g., syntax errors)126: Command invoked cannot execute (permission issues)127: Command not found128: Invalid argument to exit130: Script terminated by Ctrl+C (SIGINT)- Other codes can be defined by specific commands or scripts to indicate different types of errors.
Usage in Scripts
Exit statuses are often used in scripts to control the flow of execution. For example:
#!/bin/bash
command1
if [ $? -eq 0 ]; then
echo "command1 succeeded."
else
echo "command1 failed."
fi
Using with Conditional Statements
You can use exit statuses in conditional statements to determine the next steps in a script:
command1 && command2 # command2 runs if command1 succeeds
command1 || command2 # command2 runs if command1 fails
Summary
- Exit statuses provide a way to determine the outcome of command execution.
- A status of
0indicates success, while non-zero values indicate various types of errors. - They are essential for error handling and control flow in shell scripts.
