Computer Science Atlas
Snippets

Bash: 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:

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:

type bash $ echo $?
$ 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:

type foo $ echo $?
$ type foo
foo not found
$ $  echo $?
1

References