2

I have the following two chunks of code, I am not so sure what $? and $# stand for. Please help.

CODE ONE

 #!/bin/bashUSERID="$1" 
 /bin/id $USERID 2>/dev/null
[ $? -eq 0 ] && echo "User found" || echo "User not found"

/bin/id -g $USERID 2>/dev/null
[ $? -eq 0 ] && echo "Group found" || echo "Group not found"    `


$ cat > mtable

CODE TWO

#!/bin/sh
#
#Script to test for loop
#
#
if [ $# -eq 0 ]
then
echo "Error - Number missing form command line argument"
echo "Syntax : $0 number"
echo "Use to print multiplication table for given number"
exit 1
fi
n=$1
for i in 1 2 3 4 5 6 7 8 9 10
do
echo "$n * $i = `expr $i \* $n`"
done

Thank you

Good Person
  • 1,437
  • 2
  • 23
  • 42
xczzhh
  • 658
  • 1
  • 8
  • 22

2 Answers2

7

$? gives you the return code of the previous command executed.

$# give you the number of command line arguments given to the script.

So, basically that if condition checks if the number of arguments given were proper or not.

shadyabhi
  • 16,675
  • 26
  • 80
  • 131
4

Have a look at the man page for bash:

$# Expands to the number of positional parameters in decimal

$? Expands to the status of the most recently executed foreground pipeline.

Community
  • 1
  • 1
Miquel
  • 15,405
  • 8
  • 54
  • 87