I know these are few special variables used by bash. But I am not able to understand them.
Can anyone explain what these variables are and how to use them?
$*
$@
$#
I know these are few special variables used by bash. But I am not able to understand them.
Can anyone explain what these variables are and how to use them?
$*
$@
$#
When you call a shell script from the command line, you can pass it additional arguments called Positional Parameters. For example, when entering the following in the command line to run the script myscript.sh
:
./myscript.sh param1 param2
The variables would have the following values:
"$0" = "./myscript.sh"
"$1" = "param1"
"$2" = "param2"
The variable $#
gives the number of parameters, not including the command. In this example:
"$#" = 2
The variable $*
lists all the parameters as a single word (quotes added to emphasize string boundaries):
"$*" = "param1 param2"
The variable $@
lists each parameter as a separate quoted string (quotes added to emphasize string boundaries):
"$@" = "param1" "param2"
Note that you should almost always quote variables in bash, so you should use "$@"
and not $@
. See this programming guide for more information.