Table of contents
Exiting from a Bash script properly is important for carrying the outcome of your script to the system and to other scripts or processes that might depend on its results. The exit
command is used to terminate a Bash script and to return a status code to the calling environment. Status codes are integers from 0 to 255, where a 0 status code usually signifies success, while any non-zero status code indicates an error or specific exit condition.
The syntax of exit command
is:
exit [n]
n
is an optional exit status (a number) that the script returns to the calling process.Without
n
, the script exits with the exit status of the last executed command.
Exiting with an Implicit Success Status
If your script has completed successfully and you don't need to specify a particular exit status, you can simply use exit
without an argument. This will exit with a status of 0, indicating success.
#!/bin/bash
echo "Script executed successfully."
exit
Exiting with a Specific Status
To indicate a specific outcome or error, you can exit with a non-zero status. You should document what each status code means for your script.
#!/bin/bash
if [ ! -f "/path/to/your/file" ]; then
echo "File not found!"
exit 1 # Exits with a status of 1 to indicate the error.
else
echo "File found."
exit 0 # Exits with a status of 0 to indicate success.
fi
File found:
Using exit
in Functions
You can use exit
within a function to terminate the script from that point, not just the function.
#!/bin/bash
function check_file {
if [ ! -f "$1" ]; then
echo "File not found!"
exit 2 # Exits the entire script with status 2.
fi
}
check_file "/path/to/your/file"
echo "This line will not be executed if the file is not found."
File found:
Capturing Exit Status of Commands
You can capture the exit status of a command using $?
and use it to make decisions or exit based on that status.
#!/bin/bash
grep "someText" someFile.txt
if [ $? -ne 0 ]; then
echo "Text not found."
exit 3
else
echo "Text found."
fi
Text found:
Exiting from a Script with the Status of the Last Command
You can exit a script and automatically return the exit status of the last command executed in the script using exit $?
.
#!/bin/bash
cp /source/file /destination/file
echo "Status of the last executed command:" $?
exit $? # Exits with the status of the `cp` command.
Best Practices
Always document what each exit status code means if you use specific codes.
Use exit status codes consistently across your scripts for maintainability.
Remember that exiting from a script in a subshell (e.g., within
$(...)
or backticks) will not exit the parent script.Use the
set -e
command at the beginning of your script, which causes the script to exit immediately if any command exits with a non-zero status. This helps to avoid situations when your last command exits successfully but your previous commands have failed.
By following these guidelines, you can ensure that your Bash scripts exit gracefully and meaningfully, making them more robust and easier to integrate with other scripts and system processes.
Difference between exit and return commands
In Bash scripts, both exit
and return
statements are used to exit from a block of code, but they serve different purposes and are used in different contexts:
exit
Statement
Purpose: The
exit
statement is used to terminate the current shell session. When used in a script, it causes the script to end and returns control to the parent process (usually the shell or another script that called it).Usage: You specify
exit
followed by an optional exit status (an integer from 0 to 255), where0
typically indicates success, and any non-zero value indicates an error. If no exit status is specified,exit
returns the status of the last command executed.Scope: When
exit
is used in a script, it terminates the entire script, regardless of where it is called (main body or within a function).
Example:
#!/bin/bash
function cleanup {
echo "Cleaning up."
exit 0 # Exits the script with a success status.
}
echo "Starting script."
cleanup
echo "This line will not be executed."
return
Statement
Purpose: The
return
statement is used to exit from a function and optionally return a value to the calling section of the script. It is similar to the return statement in other programming languages used within functions or methods.Usage: Within a function, you specify
return
followed by an optional exit status. This status can be captured by the caller if the function is called in a subshell or used in a conditional expression.Scope: The
return
statement only exits from the function in which it is called. The script continues executing from the point where the function was called.
Example:
#!/bin/bash
function divide {
if [ $2 -eq 0 ]; then
echo "Division by zero error."
return 1 # Returns from the function with an error status.
else
result=$(( $1 / $2 ))
echo "Result: $result"
return 0 # Returns from the function with a success status.
fi
}
divide 10 2
echo "Function returned with status $?"
divide 10 0
echo "Function returned with status $?"
Key Differences
Context:
exit
is used to terminate the script, whilereturn
is used to exit from a function.Effect: Using
exit
stops the script execution entirely, whereasreturn
only stops the execution of the current function and returns control to the calling code.Return Value: Both
exit
andreturn
can specify an exit status, but the context in which this status is used or relevant differs.
The choice between exit
and return
depends on whether you want to terminate the entire script or just exit from a function. Understanding these differences is crucial for proper control flow and error handling in Bash scripting.