[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: |
Fri, 16 Aug 2024 18:29:23 -0400 |
On Fri, Aug 16, 2024, at 12:59 PM, freek--- via Bug reports for the GNU Bourne
Again SHell wrote:
> Description:
>
> Using the following script with a function
>
> #!/bin/bash
> init() {
> [ -n "$@" ] && echo $@
> }
> init $@
>
> and calling the script as follows:
>
> :~> LC_ALL=C . ./test.sh a b c d
>
> gives the following error:
>
> bash: [: too many arguments
There is no problem with "$@" or functions here. The "problem" is
that "$@" expands to multiple fields when there are two or more
positional parameters, so (as the error message says) you end up
running test(1) with too many arguments. This is a usage error.
$ set -x a b c d
$ test -n "$@"
+ test -n a b c d
bash: test: too many arguments
> Fix:
>
> When assigning $@ to a parameter p and using that parameter as "$p"
> instead of "$@"
> it works OK.
When you do that, you end up with only one field because neither
the assignment nor the subsequent expansion is a context in which
splitting is performed, and test(1) is run with a valid number of
arguments.
$ set -x a b c d
$ p=$@
+ p='a b c d'
$ test -n "$p"
+ test -n 'a b c d'
This behavior is all expected. There is no bug.
What are you trying to test for, anyway? Whether there are any
positional parameters? The latter test (which you claim "works
OK") does succeed when there are nonempty positional parameters,
but it also succeeds when there are multiple parameters that are
all empty, and it fails when there is a single empty parameter.
$ set '' '' ''
$ p=$@
$ test -n "$p"; echo "$?"
0
$ set ''
$ p=$@
$ test -n "$p"; echo "$?"
1
--
vq