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:
- STATUS is an optional parameter that sets the exit status of the script
- The exit status tells other programs whether the script executed successfully or not
- It will default to either 0 or the exit status of the last command executed by the script
- An exit status of 0 indicates success. Any value greater than 0 indicates a failure
Example Bash Script
Here’s an example script using the exit command, with commentary explaining what it does when used in various ways:
#!/bin/bash # A test variable which can be set to TRUE if there's an error ERROR=false # 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 fi # 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:
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.