Sometimes, your script may need to accept a command and run that command in your script. I decided to take a look at $* and $. From manpage:
- Special Parameters
* Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$" and $ expand to nothing (i.e., they are removed).
I wrote a simple script to understand better:
#!/bin/bash
echo "\$# = $# arguments"
echo
TMP=($*) ; echo -n "(\$*) => ${#TMP[]} elements => "
for arg in ${TMP[]}; do echo -n "$arg, " ; done ; echo # or in $*
TMP=("$*") ; echo -n "(\"\$*\") => ${#TMP[]} elements => "
for arg in "${TMP[]}"; do echo -n "$arg, " ; done ; echo # or in "$*"
TMP=($) ; echo -n "(\$) => ${#TMP[]} elements => "
for arg in ${TMP[]} ; do echo -n "$arg, " ; done ; echo # or in $
TMP=("$") ; echo -n "(\"\$\") => ${#TMP[]} elements => "
for arg in "${TMP[]}" ; do echo -n "$arg, " ; done ; echo # or in "$"
echo
echo 'Running:'
"$"
% ./test.sh echo abc '123 456' def
$# = 4 arguments
($*) => 5 elements => echo, abc, 123, 456, def,
("$*") => 1 elements => echo abc 123 456 def,
($) => 5 elements => echo, abc, 123, 456, def,
("$") => 4 elements => echo, abc, 123 456, def,
Running:
abc 123 456 def
"$" is the one to use.
If I need to run a short shell script:
% ./test.sh bash -c 'for((i=0;i<3;i++)); do echo -n "$i," ; done ; echo'
$# = 3 arguments
($*) => 11 elements => bash, -c, for((i=0;i<3;i++));, do, echo, -n, "$i,", ;, done, ;, echo,
("$*") => 1 elements => bash -c for((i=0;i<3;i++)); do echo -n "$i," ; done ; echo,
($) => 11 elements => bash, -c, for((i=0;i<3;i++));, do, echo, -n, "$i,", ;, done, ;, echo,
("$") => 3 elements => bash, -c, for((i=0;i<3;i++)); do echo -n "$i," ; done ; echo,
Running:
0,1,2,
Or using bash -c "$*":
% ./test.sh echo abc '123 456' def
% ./test.sh 'for((i=0;i<3;i++)); do echo -n "$i," ; done ; echo'