The positional parameters in shell are specified by parameters from $1 to $9.
To list all the positional parameters shell provides two variables : $* and $@
When not quoted, these two variables are equivalent.
However, when these variables are quoted, "$*" and "$@", they behave differently. Let us illustrate with following example
Suppose, I have two files named 'first file' and 'second file'.
I want to cat the output of two files.
These two files have space in their names.
"$*" when quoted, does not take into account any special quoting in the file names when the files are passed as parameters(here, it does not take into account the space in the file names). So $* when quoted produces a single string of all positional parameters.
But "$@" will preserve the special quoting(space in the file names, in this example). "$@" when quoted, produces a list of positional parameters.
Let us see what happens when we use $*, $@, "$*", "$@" to specify the positional parameters first file and second file
#/bin/bash
#pos.sh
cat $*
$ ./pos.sh first\ file second\ file
cat: first: No such file or directory
cat: file: No such file or directory
cat: second: No such file or directory
cat: file: No such file or directory
#/bin/bash
#pos.sh
cat $@
$ ./pos.sh first\ file second\ file
cat: first: No such file or directory
cat: file: No such file or directory
cat: second: No such file or directory
cat: file: No such file or directory
#!/bin/bash
#pos.sh
cat "$*"
$ ./pos.sh first\ file second\ file
cat: first file second file: No such file or directory
#!/bin/bash
#pos.sh
cat "$@"
$ ./pos.sh first\ file second\ file
abc
xyz
In this case, the output of first file and second file get concatenated successfully.
No comments:
Post a Comment