[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] Interesting consequence of Bash's grammar
From: |
Dan Douglas |
Subject: |
Re: [Help-bash] Interesting consequence of Bash's grammar |
Date: |
Mon, 31 Aug 2015 09:18:22 -0500 |
User-agent: |
KMail/5.0.42 pre (Linux/4.2.0; KDE/5.14.0; x86_64; ; ) |
On Thursday, August 27, 2015 8:37:51 PM CDT Stephane Chazelas wrote:
> 2015-08-27 16:09:38 +0000, Ioan-Andrei Bârsan:
> > Hello everyone,
> >
> > I was reading through Bash's source code today and looking at its grammar
> > (in `parse.y') when I noticed something peculiar. The following rule caught
> > my eye:
> >
> > function_body: shell_command
> > { $$ = $1; }
> >
> > shell_command can, among other things, be the `{ ... }` group command, but
> > it can also be an if statement, or a while loop (see line 760). This means
> > that the following statement is legal Bash:
> >
> > bar () if true; then echo "I am a weird funciton."; fi
> >
> > Is this a known/intentional feature? Wouldn't it make more sense to define
> > `function_body' based on `group_command' instead of `shell_command'?
> [...]
>
> The Bourne shell syntax to define a function is to stick
> funcname() in front of a command.
>
> It's common there to do things like:
>
> la() ls -la "$@"
>
> That's recognised by every Bourne like shell but bash, yash and
> recent versions of posh, which only allow compound commands
> there which is the minimum required by POSIX.
>
> Earlier versions of bash only recognised
>
> foo() { code; }
>
> I beleive bash was modified to be POSIX-conformant which is why
> it only recognised compound commands and not simple commands
> like other shells.
>
> I once enquired on the Austin Group mailing list (the guys
> behind POSIX) on the reason why the POSIX specification was
> funcname() compound_command and not funcname() any-command, but
> nobody could come up with an explanation.
>
ksh's `function name { ...; }` still considers the braces to be part
of the function syntax rather than a compound command. That's pretty
similar to the old-style `for ((;;)) { ...; }`, `case word { (pattern)
...; }` etc. Interpreting the braces as a command group might have been
some kind of compromise.
I'm so accustomed to thinking of command groups as being in the same
category as the others that I hardly notice when I see them omitted. The
grouping is usually clear enough from the indentation.
--
Dan Douglas
signature.asc
Description: This is a digitally signed message part.