Linux shell provides a set of variables called positional parameters that contain the individual words on the command line.
Linux Positional Parameters
Variable | Meaning |
$0 | Filename of script |
$1 - $9 | Positional parameter #1 - #9 |
${10} | Positional parameter #10 |
$# | Number of positional parameters |
${#*} | Number of positional parameters |
${#@} | Number of positional parameters |
$? | Return value |
$$ | Process ID (PID) of script |
$! | Process ID (PID) of last job run in background |
$* | Expands into the list of positional parameters, starting with 1. |
$@ | Expands into the list of positional parameters, starting with 1. |
"$*" | Expands into a doublequoted string containing all the positional parameters, each separated by the first character of the IFS shell variable (by default a space character) |
"$@" | Expands each positional parameter into a separate word surrounded by double quotes. |
#!/bin/bash #Role: Linux Positional Parameters #Author: Flasle <valinv.com@gmail.com> #Created: 2017.02.27 printParams () { echo "\$1 = $1" echo "\$2 = $2" echo "\$3 = $3" echo "\$4 = $4" echo "\$9 = $9" echo "\${10} = ${10}" } passParams () { echo -e "Number of positional parameters: $# \r\n" echo -e "Number of positional parameters with \${#*}: ${#*} \r\n" echo -e "Number of positional parameters with \${#@}: ${#@} \r\n" echo -e "\r\n" '$* --------------'; printParams $* echo -e "\r\n" '$@ --------------'; printParams $@ echo -e "\r\n" '"$*" ------------'; printParams "$*" echo -e "\r\n" '"$@" ------------'; printParams "$@" } echo -e "\r\nCurrent filename of script: $0 \r\n" echo -e "PID of script: $$ \r\n" echo -e "PID of last job run in background: $! \r\n" passParams "Hello" "everybody" "Welcome to www.valinv.com" 4 5 6 7 8 9 10 11
Output:
Current filename of script: ./valinv_www_lsp.sh PID of script: 21928 PID of last job run in background: Number of positional parameters: 11 Number of positional parameters with ${#*}: 11 Number of positional parameters with ${#@}: 11 $* -------------- $1 = Hello $2 = everybody $3 = Welcome $4 = to $9 = 7 ${10} = 8 $@ -------------- $1 = Hello $2 = everybody $3 = Welcome $4 = to $9 = 7 ${10} = 8 "$*" ------------ $1 = Hello everybody Welcome to www.valinv.com 4 5 6 7 8 9 10 11 $2 = $3 = $4 = $9 = ${10} = "$@" ------------ $1 = Hello $2 = everybody $3 = Welcome to www.valinv.com $4 = 4 $9 = 9 ${10} = 10