Re: < "$@" doesn't expand properly?
Lawrence Velázquez <[email protected]> Fri, 03 Oct 2025 19:31:50 -0400
| Newsgroups | org.kernel.vger.dash |
|---|---|
| Message-ID | <[email protected]> |
On Fri, Oct 3, 2025, at 6:47 PM, Marc Chantreux wrote:
> The simplest way to do it (I thought) was
>
> #!/bin/sh
> set -eux
> < "$@" | sponge "$1"
>
> so inplace counter awk '{$0+=2}1' would be expanded
> as
>
> < 'counter' 'awk' '{$0+=2}1' | sponge 'counter'
>
>
> but there is an error message
>
> ./inplace: 3: cannot open counter awk {$0+=2}1: No such file
>
> so it seems that the expansion leads to
>
> < 'counter awk {$0+=2}1' | sponge 'counter'
>
> is this an expected behavior?
POSIX leaves this unspecified. Section 2.7 [1] says that field
splitting is not performed on the word following a redirection
operator, and section 2.5.2 [2] says that the expansion of "$@" is
unspecified in that context.
Almost no shell works the way you are expecting, except for zsh in
native mode (which I suspect is where you first tried this syntax):
% cat /tmp/x.sh
< "$@"
% ./bash /tmp/x.sh a b
/tmp/x.sh: line 1: "$@": ambiguous redirect
% dash /tmp/x.sh a b
/tmp/x.sh: 1: cannot open a b: No such file
% ksh /tmp/x.sh a b
/tmp/x.sh[1]: a b: cannot open [No such file or directory]
% mksh /tmp/x.sh a b
/tmp/x.sh[1]: can't open a b: No such file or directory
% oksh /tmp/x.sh a b
/tmp/x.sh[1]: cannot open a b: No such file or directory
% yash /tmp/x.sh a b
yash: redirection: cannot open file `a b': No such file or directory
% zsh /tmp/x.sh a b
/tmp/x.sh:1: no such file or directory: a
% zsh --emulate sh /tmp/x.sh a b
/tmp/x.sh:1: no such file or directory: a b
[1] https://pubs.opengroup.org/onlinepubs/9799919799.2024edition/utilities/V3_chap02.html#tag_19_07
[2] https://pubs.opengroup.org/onlinepubs/9799919799.2024edition/utilities/V3_chap02.html#tag_19_05_02
--
vq