What is Exit (0)
The exit command takes a single argument, which is the status code to be returned to the shell. A status code of 0 indicates success. It is a common convention to use 0 as the status code for success and this convention is used by many programs and scripts and allows other programs and scripts to easily determine whether a command or script completed successfully or encountered an error.
# Example of using exit(0)
echo "This script completed successfully"
exit 0
What is Exit (1)
A status code of 1 indicates failure of command and again it’s a common practice to use 1 if there is any in any error or failure in command execution, here is an bash script which uses the exit (1):
# Example of using exit(1)
echo "This script encountered an error"
exit 1
What is the Difference between exit(0) and exit(1)
The main difference between exit(0) and exit(1) is the status code returned to the shell. A status code of 0 indicates that the script or command is executed successfully without encountering any sort of errors. A status code of 1 or any other non-zero value indicates that the script or command encountered an error, here is example code that use both exit(0) and exit(1):
# Check if a file exists
if [ -f "/home/aaliyan/bashfile4.sh" ]; then
echo "File exists"
sleep 5 # Delay for 5 seconds
exit_status=0 # Set exit status to success
else
echo "File does not exist"
sleep 5 # Delay for 5 seconds
exit_status=1 # Set exit status to error
fi
echo "Exit status: $exit_status"
exit $exit_status # Exit with the determined exit status
In this script, if the file exists, the script will print “File exists” and return a status code of 0 to indicate success:
If the file does not exist, the script will print “File does not exist” and return a status code of 1 to indicate an error:
Conclusion
The exit command in Bash is used to terminate a script or command and return a status code to the shell. A status code of 0 indicates success, while if the error code is any non-zero digit, then it indicates that an error is encountered. It is a common convention to use 0 as the status code for success and any non-zero value to indicate an error.