0
0
Bash Scriptingscripting~5 mins

Custom exit codes (exit N) in Bash Scripting

Choose your learning style9 modes available
Introduction
Custom exit codes help your script tell other programs or users what happened when it finished.
You want to show if a script worked or failed in a specific way.
You need to stop a script early and explain why.
You want other scripts to react differently based on your script's result.
Syntax
Bash Scripting
exit N
Replace N with a number from 0 to 255.
0 means success; any other number means an error or special condition.
Examples
Ends the script and says everything worked fine.
Bash Scripting
exit 0
Ends the script and signals a general error.
Bash Scripting
exit 1
Ends the script with a custom code 42 to show a specific error.
Bash Scripting
exit 42
Sample Program
This script checks if a file given as the first argument exists. It exits with 0 if yes, or 2 if no.
Bash Scripting
#!/bin/bash

# Check if a file exists
if [ -f "$1" ]; then
  echo "File exists."
  exit 0
else
  echo "File does not exist."
  exit 2
fi
OutputSuccess
Important Notes
Exit codes are numbers between 0 and 255 because the system uses 8 bits to store them.
Use different exit codes to help other scripts understand what happened.
Always use exit 0 for success to follow common practice.
Summary
Use 'exit N' to stop a script and send a number as the result.
0 means success; other numbers mean different errors or states.
Custom exit codes help scripts communicate clearly with each other.