How to print the last command return code in bash?

Printing the return code

To get the status of the last command executed in bash, you can check the value of $?.

$?
  • If the return code is 0 (zero), the last command execution was successful
  • All other exit codes are listed in the table below.

List of all bash return codes

Here is a list of all Bash reserved exit codes, reference: https://tldp.org/LDP/abs/html/exitcodes.html

bash command return codes

Examples

Bash getting the last command return code

Let us explore further with some examples. For this experiment, we have one file in a folder as shown below:

[email protected]:~/sample-git$ ls -ltr
total 0
-rw-rw-r-- 1 dev dev 0 Apr 27  2020 file1
[email protected]:~/sample-git$

To get a 0 return code, (success) checking whether a file exists

[email protected]:~/sample-git$ test -f file1 
[email protected]:~/sample-git$ 
[email protected]:~/sample-git$ echo $?
0
[email protected]:~/sample-git$

To get a non-zero return code, checking with a non-existing file

[email protected]:~/sample-git$ test -f file2
[email protected]:~/sample-git$
[email protected]:~/sample-git$ echo $?
1
[email protected]:~/sample-git$ 

We have used test commands for the demo, any commands will have an exit code like this.

Another example, checking the return code for the command, date

[email protected]:~/sample-git$ date
Wednesday 06 Jan 2020 01:01:13 PM IST
[email protected]:~/sample-git$ 
[email protected]:~/sample-git$ echo $?
0
[email protected]:~/sample-git$ 

That said, any commands executed in a Linux system will have a return code and that can be printed using $?