$?

From Linux Bash Shell Scripting Tutorial Wiki
Jump to navigation Jump to search

The $? (dollar question mark) is the exit status of the last task or executed command by bash. It is a particular reserved shell variable that you can use to find out if your last executed command failed or not. Let us see what does shell variable $? mean in bash and how to use it in your scripts.

Exit Status

  • Every Linux or Unix command, application, and shell statement executed has an exit status associated with it.
  • The exit status is an integer variable which is saved in the shell reserved variable called $?
  • A 0 (zero) value for the exit status indicates the command ran successfully without any errors.
  • A nonzero value for the exit status indicates failure. In other words, a command or task failed.

How to print $? exit status value

Use the printf or echo command:

echo $?
printf "%d\n" $?

Examples

In this example, I am going to search for 'vivek' word in /etc/passwd file and then print the exit status of the grep command:

grep vivek /etc/passwd
echo $?

Another example:

grep nonexistentuser /etc/passwd
echo $?

The exit status also works when you redirect output to /dev/null or hide it using some other mechanism:

grep vivek /etc/passwd >/dev/null
echo $?
## or ##
grep -q nonexistentuser /etc/passwd
echo $?
What does $? Mean in bash?
What does $? Mean in bash?

Making decision using if statement

Let us print a message when we find 'vivek' word in /etc/passwd file using if statement:

#!/bin/bash
if grep -q '^vivek' /etc/passwd
then
	echo 'Found vivek!'
else
	echo 'Sorry!'
fi
Understanding $? (dollar question mark) in shell scripts
Understanding $? (dollar question mark) in shell scripts