sajad torkamani

What is an exit code?

An exit code is a number between 0 and 255 that indicates the status of a command.

Here are common exit codes:

CodeMeaning
0Success
1General error
2Invalid arguments / misuse of shell built-ins
127Command not found
128Invalid exit argument

How to get the exit code?

You can get the exit code from the last command with:

echo $?

For example, run the ls command and pass it a non-existent directory:

ls blahblah

And then print the exit code:

echo $?

You should see the exit code of 1 which means there was an error with the last command.

Here’s a move involved example of using an exit code to do something:

#!/usr/bin/env bash

host=sajadtorkamani.com
ping -c 1 $host > /dev/null
return_code=$?

if [ "$return_code" -eq "0" ]; then
  echo "✅  $host is reachable"
else
  echo "❌  $host is unreachable"
fi
Tagged: Bash