0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use Exit Code in Bash: Syntax and Examples

In bash, you use the exit command to set an exit code that indicates success or failure of a script or command. You can check the exit code of the last command using the special variable $? to make decisions in your script.
📐

Syntax

The exit command ends a bash script and returns a number called the exit code. This code tells the system if the script succeeded or failed.

  • exit N: Ends the script with exit code N, where N is a number from 0 to 255.
  • 0 means success.
  • Any non-zero number means an error or failure.

You can check the exit code of the last command using $?.

bash
exit N
💻

Example

This example shows how to run a command, check its exit code, and use exit to end the script with that code.

bash
#!/bin/bash

# Run a command
ls /tmp

# Check exit code of ls
if [ $? -eq 0 ]; then
  echo "Command succeeded"
  exit 0
else
  echo "Command failed"
  exit 1
fi
Output
file1.txt file2.log Command succeeded
⚠️

Common Pitfalls

Common mistakes when using exit codes in bash include:

  • Not checking $? immediately after the command, which can lead to wrong results.
  • Using exit codes outside the 0-255 range.
  • Assuming any non-zero exit code means the same error.

Always check $? right after the command you want to test.

bash
# Wrong way: checking $? after another command
ls /tmp
# Some other command
pwd
if [ $? -eq 0 ]; then
  echo "pwd succeeded"
fi

# Right way: check $? immediately
ls /tmp
if [ $? -eq 0 ]; then
  echo "ls succeeded"
fi
Output
ls succeeded
📊

Quick Reference

CommandDescription
exit NExit script with code N (0 = success, non-zero = error)
$?Holds exit code of last command
if [ $? -eq 0 ]Check if last command succeeded
if [ $? -ne 0 ]Check if last command failed

Key Takeaways

Use exit N to end a bash script with a specific exit code.
Check the exit code of the last command immediately using $?.
Exit code 0 means success; any non-zero means failure or error.
Avoid checking $? after running other commands.
Use exit codes to control script flow and signal success or failure.