bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: $@ in function gives error


From: Greg Wooledge
Subject: Re: $@ in function gives error
Date: Sat, 17 Aug 2024 09:04:11 -0400

On Sat, Aug 17, 2024 at 12:41:45 +0200, Freek de Kruijf wrote:
> Apparently I have a problem with the concept of $@, I see it as list of zero 
> or more non-whitespaced elements, and quotes around it makes it into a single 
> element. Like a parameter p with a content of zero or more non-whitespaced 
> elements, where the quotes make in into a single element.
> 
> Thanks for teaching me this concept. It must have some meaning in more 
> complicated situations.

In a nutshell:

    "$*"   All of the parameters joined together with spaces between them.
    "$@"   All of the parameters expanded as a list of zero or more words.
    $*     Usually a bug.
    $@     Usually a bug.

The unquoted forms undergo THREE rounds of expansion.  First, each
parameter is expanded as a separate word, like "$@" does.  Then, each
of those words undergoes word splitting using IFS, to generate a second
list of words.  Finally, each of those words undergoes filename expansion
(globbing) to generate a third list of words.  The final result is that
third list.

You almost never want that.

Here's an illustration of how they work:

hobbit:~$ set -- "a b" "" "files matching foo.p*"
hobbit:~$ printf '<%s> ' "$*" ; echo
<a b  files matching foo.p*> 
hobbit:~$ printf '<%s> ' "$@" ; echo
<a b> <> <files matching foo.p*> 
hobbit:~$ printf '<%s> ' $* ; echo
<a> <b> <files> <matching> <foo.pdf> <foo.pl> <foo.png> 
hobbit:~$ printf '<%s> ' $@ ; echo
<a> <b> <files> <matching> <foo.pdf> <foo.pl> <foo.png> 

As documented, "$*" gives one big string, "$@" gives a list of strings,
and the unquoted forms give... that.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]