help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Interesting consequence of Bash's grammar


From: Greg Wooledge
Subject: Re: [Help-bash] Interesting consequence of Bash's grammar
Date: Thu, 27 Aug 2015 13:54:39 -0400
User-agent: Mutt/1.4.2.3i

On Thu, Aug 27, 2015 at 04:09:38PM +0000, Ioan-Andrei Bârsan wrote:
> 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?

Yes.  Some people even use it on purpose, like:

foo() (
  # This function always runs in a subshell, so we can run amok with
  # transient side effects.
  shopt -s stuff
  cd somewhere
  PATH=things
  ...
)

I do not recommend this.  It makes your code very hard to read.

> Wouldn't it make more sense to define
> `function_body' based on `group_command' instead of `shell_command'?

Changing the grammar to protect people from their own misuse of the
language isn't really necessary, in my opinion.  Good programmers will
avoid doing stupid things, and bad programmers will fail to avoid them.

Choose to be a good programmer.  Don't ask the language to force you to
be one.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]