Checking Command Exit Status in Bash
In Bash, the exit status of the last executed command is stored in the special variable $?
. You can use this variable to check the exit status of a command and take appropriate actions based on the result.
Checking the Exit Status Directly
To check the exit status of the last executed command, you can simply echo the value of the $?
variable:
command_to_execute
echo $?
If the command executed successfully, the output will be 0
. If the command encountered an error, the output will be a non-zero value.
Using Conditional Statements
You can use conditional statements, such as if-else
or case
, to check the exit status and perform different actions based on the result:
command_to_execute
if [ $? -eq 0 ]; then
echo "Command executed successfully"
else
echo "Command failed with exit status $?"
fi
In this example, the if
statement checks if the exit status ($?
) is equal to 0
. If it is, the command executed successfully, and the script prints a success message. If the exit status is non-zero, the script prints an error message along with the exit status.
Checking the Exit Status Directly in the Condition
You can also check the exit status directly in the conditional statement, without using the $?
variable:
if command_to_execute; then
echo "Command executed successfully"
else
echo "Command failed with exit status $?"
fi
In this case, the exit status of the command_to_execute
is directly checked in the if
statement. If the command executes successfully (exit status 0), the then
block is executed. If the command fails (non-zero exit status), the else
block is executed.
By understanding how to check the exit status of commands in Bash, you can write more robust and reliable shell scripts that can handle errors and take appropriate actions based on the outcome of each command.