Home » Linux » Shell » Bash Exit Script

Exiting Bash Scripts with the exit Command, With Examples

Bash/Shell scripts usually run sequentially until all of the code in the file has been executed. The exit command will exit the script before this based on conditions of your choosing.

exit Command Syntax

Here’s the syntax for the exit command, which can be used in Bash/Shell scripts:


Note that:

  • STATUS is an optional parameter that sets the exit status of the script

Example Bash Script

Here’s an example script using the exit command, with commentary explaining what it does when used in various ways:


# A test variable which can be set to TRUE if there's an error

# This line will always be printed as it comes before any exit command
echo "Hello LinuxScrew!"

# If there is an error...
if $ERROR ; then

    # Tell the user there was an error
    echo "There was an error"

    # Exit the program with a status of 1 (Indicating the script did not succeed)
    exit 1


# Exit the script with a status of 0 (Indicating the script did succeed)
exit 0

# This line will never be printed as it follows an exit command, so it will never run
echo "This is a pointless line"

What is the ‘#!’ in Linux Shell Scripts?

As shown, exit is a simple command that just exits the script, with a status that can be checked later to see if the script succeeded.

Checking the Exit Status of a Program or Script

The exit status of the last run command can be accessed from the shell with the following command:

echo $?

What About Output from the Script?

Output from the script is separate from the exit status. Program output and the output from commands like echo will all have been output by the application using STDOUT – which can then be redirected, viewed, and saved.

Photo of author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment