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 $?
$# : 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.
$1 is the argument passed for shell script. Suppose, you run ./myscript.sh hello 123. then. $1 will be hello. $2 will be 123.
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 .
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.
$?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With