Introduction
Exit is often needed in the Bash script to terminate its execution. Exiting from a script, when required, is necessary. This way the script runs as expected, conserves system resources, and helps to debug. For example, scripts that perform a backup of data need to exit after the backup is complete so as to prevent overwriting the files.
In this guide, we learn about the bash exit command with examples of scripts.
Exit Command
By the name itself, it is clear that to terminate the script, we have the exit command. When executed, it causes the shell session that is running the script to terminate. The control is then returned to the parent shell.
Syntax:
exit [n]
The exit command takes an optional exit status code as an argument. This code is sent to the parent shell as the exit status of the script. Zero indicates success, while a non-zero exit status implies failure.
Example:
exit
exit 5
The exit command, without an argument, ends the current shell session or script. The shell simply exits with the exit status of the last executed command.
When the latter command executes, the shell terminates with the exit status as 5.
Different Exit Status Codes
We have tabulated the commonly used status codes:
Exit Code | Description |
---|---|
0 | Successful exit without errors |
1 | One or more generic errors encountered upon exit |
2 | Incorrect usage, such as invalid options or missing arguments |
126 | Command found but is not executable |
127 | Command not found, usually the result of a missing directory in $PATH variable |
128+N | Command encountered a fatal error. It was forcefully terminated manually or from the outside. N tells us which signal was received. |
130 | Command terminated with signal 2 (SIGINT) (ctrl+c on keyboard). 128+2 |
143 | Command terminated with signal 15 (SIGTERM) (kill command). 128+15 |
We can use the echo $?
command to see the exit code.
Examples
In this section, we will learn how we can exit from the bash script.
Exit Command with Arguments
The exit command can accept an optional argument. This argument is called the exit status code. It lies between 0 to 255 and indicates the success or the failure of the script. By convention, an exit status code of 0 indicates success, while any other value indicates failure.
Let us develop a bash script with a function to divide two numbers and print the result. We will use exit 1 to terminate the script if the divisor is zero.
Example:
#!/bin/bash
function divide() {
if [ $2 -eq 0 ]; then
echo "Can’t divide by zero"
exit 1
fi
local result=$(($1 / $2))
echo "Result: $result"
exit 0
}
divide 8 2
divide 8 0
- Function f performs the division of two numbers.
- If the second number is zero, the function prints an error message. The exit command terminates the entire script. The exit status code is 1.
- If a non-zero number is provided, we will calculate the integer division and return the result using return.
- When called with arguments 8 and 2, it will calculate the result 4 and return it using return.
- We print the result using $?. It retrieves the exit status code of the last executed command which is 4.
- When called with 8 and 0, it prints an error message and terminates the entire script using exit. The exit status code is 1 this time.
Exit from Conditional Statements
We can use exit to terminate from conditional statements. We normally use this technique to end the script if no argument is provided.
Let us have a simple script to check the number of arguments provided to the script. The script will terminate using the exit command if it finds zero arguments.
Example:
#!/bin/bash
if [ $# -eq 0 ]
then
echo "No arguments entered."
exit
fi
echo "Total arguments: $@"
- We use an if statement to verify if any command-line arguments were provided to the script.
- We check this using the special variable $# variable. This counts the number of arguments.
- If no argument is made available, we print an error message.
- We then use exit and terminate the script immediately.
- If arguments were provided, we print them to the console using echo.
Exit Traps
As the name suggests, exit traps enable us to execute specific commands immediately before exiting the script. It is independent of the reason for the exit. It could be due to an error, a user interrupt, or a straight exit. This can be helpful to log tasks before the script terminates.
To set up an exit trap, we have the trap command. This way we can specify a command when the script exits.
We are going to create a script to set up a function and use the trap command to associate it with the exit signal. This signal gets triggered when the script is on the cusp of exiting.
Example:
#!/bin/bash
function logger() {
echo "Cleaning up before exit"
}
trap logger EXIT
echo "One"
echo "Two"
- The logger function performs some cleanup tasks before the script exits.
- We then use the trap command to specify that the logger function should be executed when the script exits.
- The EXIT keyword informs Bash that the logger function should be executed when the script exits.
- The script prints One and then Two.
Handling exits
Depending upon our requirements, we can handle the exits either when any of the commands fail or only for a specific command. We will go through these scenarios one by one.
Exiting when any command fails
The set command with -e option terminates the script immediately. This happens when any command within the script fails. This is useful in case of critical errors when we don't want the script to run further, especially when developing backup scripts to prevent overwriting of the same file in case of any error.
Let us write a script with set -e command that causes its termination immediately if any command returns a non-zero exit status.
Example:
#!/bin/bash
set -e
echo "pwd"
pwd
echo "dwp"
dwp
echo "ls"
ls
- We have made use of the set -e option.
- This is to ensure that the script exits immediately, if there’s any error.
- If any of the commands - pwd, dwp, or ls command fails, the script will immediately exit.
- The second command - dwp is an invalid command.
- The script will exit with an error message on the console.
- The script will not go to the ls command.
The "set -e" command at the start of the script enables this feature to the complete script. For a specific block of code, we must start with the "set -e" and end with the "set +e" command.
Exiting only when specific commands fail
In the previous section, we saw the usage of the set -e option to exit the script immediately in case of any failure. But, Bash is flexible and can be configured to exit only when specific commands fail.
We make use of the || operator. Bash will execute a command if the previous command fails, and then exit the script. We can use this technique to exit with an error message.
Let us understand the below script that executes and checks the exit statuses using the || operator. The script displays an error message and then exits, in case any command fails.
Example:
#!/bin/bash
pwd || { echo "pwd failed"; exit; }
echo "pwd successful"
dwp || { echo "dwp failed"; exit; }
echo "dwp successful"
ls || { echo "ls"; exit; }
echo "ls successful"
- The || operator is used to execute a command if the previous command fails.
- The script prints an error message and exits if the pwd command fails.
- If successful, the script displays a success message and moves to the next line.
- The same procedure is repeated for dwp and ls commands respectively.
We don't require the set -e option in this case. We are manually checking the exit status of each command and exiting the script if there’s a failure. The curly braces around the commands and the semicolon after the closing brace are important. This groups the commands together and ensures that the exit command applies to the entire group.
Difference between exit and return
Both the exit and the return commands terminate a function or a script.
Exit ends the entire script, while return terminates a function and returns a value to the calling function or script.
The exit command terminates the entire Bash script. When exit is executed, the script will terminate and return an exit status code. This code indicates the success or failure of our script. The exit status code can be accessed by the parent process that called the script. This helps determine the outcome of the script execution.
The return command will only terminate the current function and return a value to the calling function or script. This command can only be within a function. It passes a value back to the calling function or script. When called, the function stops executing. The value passed to return will be returned to the calling function or script.
Let us consider a script that has a function to divide two numbers and return the quotient. We will use exit 1 to terminate the script if the divisor is zero.
Example:
#!/bin/bash
function f()
{
if [ $1 -eq 0 ]
then
echo "Can’t divide by zero"
exit 1
fi
local result=$(($1 / $2))
return $result
}
f 8 2
echo "Result of function is $?"
f 8 0
echo "Result of function is $?"
- Function f performs the division of two numbers.
- If the second number is zero, the function prints an error message. The exit command terminates the entire script. The exit status code is 1.
- If a non-zero number is provided, we will calculate the integer division and return the result using return.
- We call the function twice.
- When called with arguments 8 and 2, it will calculate the result 4 and return it using return.
- We print the result using $?. It retrieves the exit status code of the last executed command which is 4.
- When called with 8 and 0, it prints an error message and terminates the entire script using exit. The exit status code is 1 this time.
Comments