Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does '$?' mean in bash scripts? [duplicate]

Tags:

syntax

bash

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 $?
like image 637
Meekohi Avatar asked Apr 05 '12 16:04

Meekohi


People also ask

What does $# mean in shell script?

$# : This variable contains the number of arguments supplied to the script. $? : The exit status of the last command executed. Most commands return 0 if they were successful and 1 if they were unsuccessful. Comments in shell scripting start with # symbol.

What does echo $1 mean?

$1 is the argument passed for shell script. Suppose, you run ./myscript.sh hello 123. then. $1 will be hello. $2 will be 123.

What is $1 and $2 in shell script?

These are positional arguments of the script. Executing ./script.sh Hello World. Will make $0 = ./script.sh $1 = Hello $2 = World. Note. If you execute ./script.sh , $0 will give output ./script.sh but if you execute it with bash script.sh it will give output script.sh .

What is $? In Linux?

The $? variable represents the exit status of the previous command. Exit status is a numerical value returned by every command upon its completion. As a rule, most commands return an exit status of 0 if they were successful, and 1 if they were unsuccessful.


1 Answers

$?

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.

like image 183
user unknown Avatar answered Oct 12 '22 11:10

user unknown