$# $n
$# - number of arguments$n - nth argument. $0 contains the full pathname of the first item on the command line (i.e., the name of the program).
To
specify a number greater than nine, surround the number in braces, as in ${10}, ${55}, ${211}, and so on.
#!/bin/bash# posit-param: script to view command line parametersecho "Number of arguments: $#\$0 = $0\$1 = $1\$2 = $2\$3 = $3\$4 = $4\$5 = $5\$6 = $6\$7 = $7\$8 = $8\$9 = $9\$10 = ${10}"
shift
Each time shift is executed, the value of $2 is moved to $1, the value of
$3 is moved to $2, and so on. The value of $# is also reduced by one.
#!/bin/bash# posit-param2: script to display all argumentscount=1while [[ $# -gt 0 ]]; doecho "Argument $count = $1"count=$((count + 1))shiftdone
Examples
#!/bin/bash# file-info: simple file information programPROGNAME="$(basename "$0")"if [[ -e "$1" ]]; thenecho -e "\nFile Type:"file "$1"echo -e "\nFile Status:"stat "$1"elseecho "$PROGNAME: usage: $PROGNAME file" >&2exit 1fi
Using Positional Parameters with Shell Functions
!/bin/bash#************************************************# Author: Ronnie Ming# Filename: posit_param.sh# Date: 2021-05-04 16:11:19# Description: ...#************************************************function file_info() {if [[ -e "$1" ]]; thenecho -e "\nFile Type:"file "$1"echo -e "\nFile Status:"stat "$1"elseecho "$FUNCNAME: usage: $FUNCNAME file" >2&return 1fi}file_info posit_param.sh
Note that $0 always contains the full pathname of the first item on the command line (i.e., the name of the program)
and does not contain the name of the shell function.
Handling Positional Parameters en Masse
| Parameter | Description |
|---|---|
| $* | Expands into the list of positional parameters, starting with 1. When surrounded by double quotes, it expands into a double-quoted string containing all of the positional parameters, each separated by the first character of the IFS shell variable (by default a space character). |
| $@ | Expands into the list of positional parameters, starting with 1. When surrounded by double quotes, it expands each positional parameter into a separate word as if it was surrounded by double quotes. |
#!/bin/bash# posit-params3: script to demonstrate $* and $@print_params() {echo "\$1 = $1"echo "\$2 = $2"echo "\$3 = $3"echo "\$4 = $4"}pass_params() {echo -e "\n" '$* :'; print_params $*echo -e "\n" '"$*" :'; print_params "$*"echo -e "\n" '$@ :'; print_params $@echo -e "\n" '"$@" :'; print_params "$@"}pass_params "word" "words with spaces"
$ ./posit-param3$* :$1 = word$2 = words$3 = with$4 = spaces"$*" :$1 = word words with spaces$2 =$3 =$4 =$@ :$1 = word$2 = words$3 = with$4 = spaces"$@" :$1 = word$2 = words with spaces$3 =$4 =
"$@" is by far the most useful for most situations
because it preserves the integrity of each positional parameter.
