Computer Science Atlas
Code Review

Bash Examples: Get the Exit Status Code of the Last Command

February 13, 2021
 

Table of Contents

$?

$?

In a Bash shell, the exit status (a.k.a. exit code or return code) of the last command you ran is stored in the special parameter $?. In a terminal session, you can print out that value using echo:

Bash
Copy
echo $?
$
echo $?

As an example, let's run the type command and then get its exit status. The type command in Bash provides information about a specific command.

If the command is valid (exists), then type exits with status 0:

Terminal
Copy
$  type bash
bash is /usr/bin/bash
$  echo $?
0
$  type bash
bash is /usr/bin/bash
$  echo $?
0

If the command is not valid (does not exist), then type exits with status 1. Here, we'll assume that you don't have a program or command called foo:

Terminal
Copy
$  type foo
-bash: type: foo: not found
$  echo $?
1
$  type foo
-bash: type: foo: not found
$  echo $?
1

References