What does '$?' mean in bash scripts?

Go To StackoverFlow.com

16

Possible Duplicate:
What does “$?” give us exactly in a shell script?

What does $? mean in a bash script? Example below:

#!/bin/bash
# userlist.sh

PASSWORD_FILE=/etc/passwd
n=1           # User number

for name in $(awk 'BEGIN{FS=":"}{print $1}' < "$PASSWORD_FILE" )

do
  echo "USER #$n = $name"
  let "n += 1"
done

exit $?
2012-04-05 16:08
by Meekohi
The return value/exit status of the most recently executed command - Michael Berkowski 2012-04-05 16:09
Ah sorry for the duplicate. "$?" is hard to search for - Meekohi 2012-04-05 19:40


18

$?

is the last error (or success) returned:

$?
1: command not found.
echo $?
127

false 
echo $?
1

true 
echo $?
0

The exit in the end:

exit $?

is superfluous, because the bash script will exit with that status anyway. Citing the man page:

Bash's exit status is the exit status of the last command executed in the script.

2012-04-05 16:15
by user unknown
Thanks for adding that the exit $? is superfluous - trueCamelType 2013-06-18 15:27
Ads