0
0
Bash Scriptingscripting~5 mins

Exit codes ($?) in Bash Scripting

Choose your learning style9 modes available
Introduction
Exit codes tell us if a command worked or failed. They help scripts decide what to do next.
Check if a file was copied successfully before moving on.
Verify if a program ran without errors before starting another task.
Detect if a command failed and show a friendly message to the user.
Stop a script early if a critical step did not complete correctly.
Syntax
Bash Scripting
echo $?  # shows the exit code of the last command
Exit code 0 means success; any other number means an error.
Always check $? right after the command you want to test.
Examples
Lists files in /tmp and then prints the exit code. 0 means success.
Bash Scripting
ls /tmp
 echo $?
Tries to list a non-existing folder, then prints exit code. Non-zero means error.
Bash Scripting
ls /not_exist
 echo $?
Creates a folder and prints exit code to confirm success.
Bash Scripting
mkdir newfolder
 echo $?
Sample Program
This script creates a folder and checks if it worked using exit codes. Then it removes the folder and checks again.
Bash Scripting
#!/bin/bash

mkdir testfolder
if [ $? -eq 0 ]; then
  echo "Folder created successfully."
else
  echo "Failed to create folder."
fi

rm -r testfolder
if [ $? -eq 0 ]; then
  echo "Folder removed successfully."
else
  echo "Failed to remove folder."
fi
OutputSuccess
Important Notes
Always check the exit code immediately after the command you want to verify.
Use exit codes in scripts to handle errors gracefully and avoid surprises.
Common exit codes: 0 = success, 1 = general error, other numbers can mean specific errors.
Summary
Exit codes tell if a command worked or failed.
0 means success; other numbers mean errors.
Check $? right after a command to get its exit code.