Date: Mon, 21 Mar 2011 02:43:45 +1100 (EST) From: Ian Smith <smithi@nimnet.asn.au> To: Maxim Khitrov <max@mxcrypt.com> Cc: freebsd-questions@freebsd.org Subject: Re: Shell script termination with exit function in backquotes Message-ID: <20110321022004.L36648@sola.nimnet.asn.au> In-Reply-To: <20110320120022.DAC7C10657C1@hub.freebsd.org> References: <20110320120022.DAC7C10657C1@hub.freebsd.org>
next in thread | previous in thread | raw e-mail | index | archive | help
in freebsd-questions Digest, Vol 354, Issue 10, Message: 4 On Sat, 19 Mar 2011 12:15:26 -0400 Maxim Khitrov <max@mxcrypt.com> wrote: > Here's another, but related, problem that I just ran into. The man page reads: > > Commands may be grouped by writing either > (list) > or > { list; } > The first form executes the commands in a subshell. Note that built-in > commands thus executed do not affect the current shell... > > Here's my script: > > ---- > #!/bin/sh > > { A=1; }; echo $A > echo | { B=2; }; echo $B > { C=3; } > /dev/null; echo $C > ---- > > And here's the output: > > ---- > 1 > > 3 > ---- > > Where did the '2' go? Again, I have to assume that when stdin is piped > to a group of commands, those commands are executed in a subshell > despite curly braces. But where is this behavior documented? It seems > that there are a lot of corner cases that can only be understood if > you are familiar with the shell implementation. Documentation can > certainly be improved in places. See sh(1) /Pipelines - last para: Note that unlike some other shells, sh executes each process in the pipe- line as a child of the sh process. Shell built-in commands are the exception to this rule. They are executed in the current shell, although they do not affect its environment when used in pipelines. The braces aren't relevant because it's a pipeline, so even without: echo | B=2; echo $B writes '', but echo | { B=2; echo $B; } or (equivalent within a pipeline) echo | ( B=2; echo $B; ) writes '2'. cheers, Ian
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20110321022004.L36648>