Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Square brackets in command position



On Sat, Jun 5, 2021 at 10:05 AM Stephane Chazelas <stephane@xxxxxxxxxxxx> wrote:
>
> 2021-06-04 17:20:29 -0700, Bart Schaefer:
> [...]
> > > array[1 + 1]=4
> > >
> > > That is pretty annoying.
> >
> > That's just shell whitespace rules, though.
>
> Note that all other shells that support a[1]=value (ksh, pdksh,
> bash) do it.

Chip will probably correct me, but from some experiments with bash it
appears that (with the exception of '[' all alone, to invoke "test")
an (unquoted) '[' in a word in command position always begins an
expression that must be bounded by a closing (unquoted) ']' (even if
that means continuing to the PS2 prompt).  Thus for example
  $ a[ 1 + 1 ]b
globs to a file named "a b" in the current directory and does a path
search to run that as a command.  Note that
 $ [a ]b
globs to "ab" or " b" (leading space there if that's hard to see),
it's not what's to the left of '[' that triggers this.

Thus it's not just assignments that have command-position magic,
character classes can have embedded (unquoted) spaces there as well.
This breaks if you are looking for a file named e.g. "a+=" because
']=' turns the whole thing into an array element assignment.

> There is variation in behaviour between shells if the first word
> starts with name[ and either a matching ] or matching ] followed
> by = is not found, and how that matching is done or what kind of
> quoting are supported inside the [...].

That doesn't give us any good ideas on where to start.  Of course
zsh's parsing hash keys using the same quoting rules as arithmetic was
a quick way to slurp hash[string] through the existing array[math]
parser at the time, and in retrospect probably should have been given
its own rules.

> In zsh, that would be even less problematic as (at least when
> not in sh emulation), zsh complains about unmatched [s or ]s

As mentioned before, that's the BAD_PATTERN setopt, which can be
turned off independent of emulation, so it might be a stretch to say
we wouldn't be breaking anything.




Messages sorted by: Reverse Date, Date, Thread, Author