Bash and bash scripts executed and terminated after execution. After the bash script execution is complete some information about the script is returned. This information is called exit status or exit code. The exit status or exit code can be also returned by using the exit command by using explicitly.
Every shell command or bash script returns an exit status or exit code in order to provide information about the command or script. Generally, the exit status or exit code is used with numbers. In general 0 is used to express the command or script execution is completed successfully. Non-zero values generally related to error and the value specifies a specific error about the command or script. Bash has a special variable that stores the latest executed script or command exit status which is $? .
If this command is executed successfully and properly the exit status is like below.
Say we try to run a command which do not exist.
The exit status is 127 which means “command not found“.
When we try to write into a file where we do not have write permissions the returned code is 1.
echo "test" > /etc/sudoers
If we try to use a non existing directory or path the exit status is 2. The returned exit status message is “No such file or directory“.
The exit command can be used to specify the exit status explicitly by overwriting the current exit status. The exit command simply terminates the current bash shell or sessions and returns the status code. An integer can be used to specify exit status. In the following example, we set the exit status as 2 by using the exit command.
bash -c "ls /nonexisting; exit 2;"