Lawrence Loh
Lawrence Loh

Reputation: 243

What is the use of $# in 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 $? 

Upvotes: 21

Views: 24276

Answers (4)

yaima herrera
yaima herrera

Reputation: 1

In bash exist special variables... and i write you some of then.

$#- this is an special variable that content inside the number of command line (you can just count how many parameters were entered) you passed to the script. tis variable also represent the last command line but its better do this ${!#}

$?- this one is very special cause its represents is your script is fine this variable holds the exit status of the previosly command... its a littler confusing but it work perfectly... when you end you script you can positional this variable at the end and if she return 0 value you scrip is perfect is true, if she return 1 or others you must check out your lines.

Upvotes: 0

Thomas Ayoub
Thomas Ayoub

Reputation: 29431

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..."

Upvotes: 34

ClaudioM
ClaudioM

Reputation: 1446

$# shows the number of the script's arguments $? shows the last script's return value

about arguments: echo "ARG[$#]" before if and then execute the script like

script.sh 1 

the ouput will be

ARG[1]
Usage: g old-pattern new-pattern filename

and so on

the ouput of $? could be also used on the command line:

#shell>ls
file1.txt        g                inpu             nodes_list
#shell>echo $?
0

#shell>ls FileNameNotFound
ls: FileNameNotFound: No such file or directory
#shell> echo $?
1

Upvotes: 3

user000001
user000001

Reputation: 33327

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.

Upvotes: 7

Related Questions