What is the use of $# in Bash

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.


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

$# 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

Tags:

Linux

Bash