In Linux, the exit status of a command or shell script is a numeric value that represents the success or failure of the command or script. The exit status is stored in the special shell variable $?
. A value of 0 indicates success, and any non-zero value indicates failure.
For example, after running the command ls /tmp
, the exit status will be 0 if the /tmp directory exists and the command was able to list its contents, and non-zero if the /tmp directory does not exist or the command was not able to list its contents.
You can check the exit status of a command by using the following syntax:
echo $?
You can also use the exit status in a shell script to control the flow of execution. For example, you can use an if
statement to check the exit status and take different actions depending on whether the command succeeded or failed:
command
if [ $? -eq 0 ]; then
echo "Command succeeded"
else
echo "Command failed"
fi
In Bash, you can set the exit status of a script by using the exit
command followed by the desired exit status. The exit status must be an integer value between 0 and 255. The following example sets the exit status to 0, indicating success:
exit 0
And the following example sets the exit status to 1, indicating failure:
exit 1
It’s important to note that the exit status is usually set by the last executed command, and that exit status will be the exit status of the script. So, if you want to set the exit status of the script, it’s important to do it before any other command that may change the exit status.