Shell Script · Exit Status

Shell Scripting · Lesson 17

Exit Status

Understand exit status in Linux commands. Use $? in scripts. Error handling technique. Build reliable automation scripts.

What is Exit Status?

Every command executed in Linux returns an exit status. It is a numeric value that tells whether a command succeeded or failed.

By convention:

  • 0 → Success
  • Non-zero → Failure

Why Exit Status Matters

Error Detection

Detect if a command ran successfully.

Flow Control

Control script execution based on success or failure.

Debugging

Helps identify which command failed.

How to Check Exit Status

check exit status
exit-status
command
echo $?

Exit Status Examples

1. Basic Exit Status

Every command returns an exit status after execution.

terminal — bash
exit-status
ls /home
echo $?

2. Success vs Failure

0 means success, non-zero means failure.

terminal — bash
exit-status
ls /home
echo "Exit status: $?"
 
ls /notexist
echo "Exit status: $?"

3. Using Exit Status in Condition

Use $? to check if a command succeeded.

terminal — bash
exit-status
mkdir testdir
 
if [ $? -eq 0 ]; then
echo "Directory created successfully"
else
echo "Failed to create directory"
fi

4. Custom Exit Codes

Use exit to define your own exit status.

terminal — bash
exit-status
if [ -f "/etc/passwd" ]; then
echo "File exists"
exit 0
else
echo "File not found"
exit 1
fi

Best Practices

Recommended Practices

  • Always check exit status for critical commands.
  • Use meaningful exit codes (0–255).
  • Avoid ignoring failures silently.
  • Use exit in scripts to stop execution when needed.

Practice Task – Exit Status

  • Write a script that checks if a file exists.
  • Exit with status 0 if found, 1 otherwise.
  • Print meaningful messages.

Next lesson: Debugging & Traps