Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of $# in Bash

Tags:

linux

bash

I am very new to Bash scripting, can someone explain to me how the $# and $? work in the following code?

#!/bin/bash

ARGS=3         # Script requires 3 arguments.
E_BADARGS=85   # Wrong number of arguments passed to script.

if [ $# -ne "$ARGS" ]
then
  echo "Usage: `basename $0` old-pattern new-pattern filename"
  exit $E_BADARGS
fi

old_pattern=$1
new_pattern=$2

if [ -f "$3" ]
then
    file_name=$3
else
    echo "File \"$3\" does not exist."
    exit $E_BADARGS
fi

exit $? 
like image 943
Lawrence Loh Avatar asked Mar 15 '16 09:03

Lawrence Loh


2 Answers

From Learn Bash in Y minutes:

# Builtin variables:
# There are some useful builtin variables, like
echo "Last program's return value: $?"
echo "Script's PID: $$"
echo "Number of arguments passed to script: $#"
echo "All arguments passed to script: $@"
echo "The script's name: $0"
echo "Script's arguments separated into different variables: $1 $2..."
like image 127
Thomas Ayoub Avatar answered Oct 07 '22 05:10

Thomas Ayoub


From https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html

$# Expands to the number of positional parameters in decimal.

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

like image 25
user000001 Avatar answered Oct 07 '22 05:10

user000001