In Bash, the exit status of a command refers to a numeric value that indicates the success or failure of the command execution. Every command that runs in the shell produces an exit status, which can be accessed through the special variable
$?. The exit status is a value between 0 and 255, where 0 represents success, and any non-zero value indicates failure or an error condition.
Here’s an example that demonstrates the usage of the exit status in Bash:
#!/bin/bash ls non_existent_file.txt if [ $? -eq 0 ]; then echo "Command executed successfully." else echo "Command failed with exit status: $?" fi
In this example, the
ls command is executed on a non-existent file
non_existent_file.txt. Since the file does not exist, the
ls command will fail, and its exit status will be non-zero. The
$? variable is then checked using the conditional statement
[ $? -eq 0 ] to determine whether the command executed successfully. If the exit status is 0, it means the command succeeded, and the corresponding code block will be executed. Otherwise, if the exit status is non-zero, it indicates a failure, and the code block following the
else keyword will be executed, printing the exit status.
When you run this script, it will output:
ls: cannot access 'non_existent_file.txt': No such file or directory Command failed with exit status: 2
The exit status can be used to determine the success or failure of a command and make decisions or perform error handling in your Bash scripts. By checking the exit status, you can control the flow of your script and take appropriate actions based on the command’s result.