View exit code of a command using the $? command in Linux

Home > Search > Linux commands
  by

$? is a special command that is used to determine the status of the last run command. $? will either be 0 (success) or 1 (failure).

~]# echo $?
0

 

As a simple example, let's say you do not have permission to shutdown the system. In this example, the exit code will be 1 (failure).

~]# shutdown now
Permission denied

~]# echo $?
1

 


Determine if a file contains a string

The grep command is used to search for a certain string in a file. If grep is able to find one or more occurrences of the string in the file, the exit code will be 0 (success).

~]# grep "hello world" example.file
hello world

~]# echo $?
0

 

On the other hand, if there are zero occurrences of the string in the file, the exit code will be 1 (failure).

~]# grep "hello world" example.file

~]# echo $?
1

 

This can be useful in a script, to do something when a file contains a certain string, or to do something else if the file does not contain a certain string.

#!/bin/bash

abc=$(grep "hello world" example.file)

result=$?

if [ $result == 0 ];
then
    echo "example.file does contain hello world"
else
    echo "example.file does not contain hello world"
fi

 


Exit code in bash script

Exit 0 and exit 1 can be used in a bash shell script to cease execution of the script. In this example, if $foo does not equal one, exit 1 is used to cease execution of the script.

#!/bin/bash

foo=1

if [ $foo -eq 1 ]
then
  echo "foo equals one, let's keep going"
else
  echo "foo does not equal one. Exiting!"
  exit 1
fi

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments