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:

dev@codetryout:~/sample-git$ ls -ltr
total 0
-rw-rw-r-- 1 dev dev 0 Apr 27  2020 file1
dev@codetryout:~/sample-git$

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

dev@codetryout:~/sample-git$ test -f file1 
dev@codetryout:~/sample-git$ 
dev@codetryout:~/sample-git$ echo $?
0
dev@codetryout:~/sample-git$

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

dev@codetryout:~/sample-git$ test -f file2
dev@codetryout:~/sample-git$
dev@codetryout:~/sample-git$ echo $?
1
dev@codetryout:~/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

dev@codetryout:~/sample-git$ date
Wednesday 06 Jan 2020 01:01:13 PM IST
dev@codetryout:~/sample-git$ 
dev@codetryout:~/sample-git$ echo $?
0
dev@codetryout:~/sample-git$ 

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