[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: $@ in function gives error
From: |
Lawrence Velázquez |
Subject: |
Re: $@ in function gives error |
Date: |
Sat, 17 Aug 2024 16:38:58 -0400 |
On Sat, Aug 17, 2024, at 6:41 AM, Freek de Kruijf wrote:
> Apparently I have a problem with the concept of $@
Greg has already tried explaining it, so I'll just focus on a few details:
> I see it as list of zero or more non-whitespaced elements
When used in a context where splitting is performed, "$@" expands
to *all* positional parameters, not just "non-whitespaced" ones.
When used in a context where splitting is not performed (like the
right-hand side of a simple assignment), both $@ and "$@" expand
to a single field comprising all the parameters concatenated with
spaces. This representation doesn't really handle parameters that
are empty or that contain spaces themselves.
$ set nospace '' 'one space'
$ p=$@
$ declare -p p
declare -- p="nospace one space"
This is not usually what you want.
> 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.
The distinctive behavior of "$@" is documented.
https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html#index-_0040
https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V3_chap02.html#tag_19_05_02
> Thanks for teaching me this concept. It must have some meaning in more
> complicated situations.
I assert the opposite sentiment. When processing the positional
parameters, multiple-field "$@" is almost always what you want, and
any other expansion is only appropriate in very specific situations.
> A test -n "$1" has also the effect I was looking for as the suggested one
> $# -ne 0 .
These commands don't agree when $1 is set to an empty value.
$ set ''
$ test -n "$1"; echo "$?"
1
$ test "$#" -ne 0; echo "$?"
0
--
vq