Shell script termination with exit function in backquotes

Jilles Tjoelker jilles at stack.nl
Tue Mar 22 22:19:24 UTC 2011


Maxim Khitrov wrote:
> [$(exit) exits the main shell environment]

This is a bug which is fixed in 9-current.

Another message:
> On Sat, Mar 19, 2011 at 12:44 PM, Devin Teske <dteske at vicor.com> wrote:
> > [all elements of multi-command pipelines are executed in a subshell]

> > You're learning that there are deviations to the rule as-mentioned
> > in the man-page.

> I've learned this a long time ago :)

> My point is that these deviations should be noted in the man page to
> help eliminate such surprises. A single sentence would have sufficed
> in this case.

The man page is not complete, but this has been in it for a while, in
the Pipelines subsection:

] Note that unlike some other shells, sh executes each process in a
] pipeline with more than one command in a subshell environment and as a
] child of the sh process.

This means that in A | B | C, three processes are created with the shell
as their common parent. (Compared to the Bourne shell, where A and B are
children of C, and to the Korn shell which executes C in the main shell
process.)

Note, PR bin/34811 requests certain first commands of pipelines (in
particular, "jobs") to be executed in the main shell environment, not as
a subshell. POSIX permits this and it may be implemented at some point.
If the pipeline has two elements, the second element could be executed
in the main shell environment as well but this could be confusing.

> > The reason for these deviations is quite simple in-fact...

> > The shell needs to create a new set of stdin/stdout file-descriptors
> > for the block of commands that you've created, and executing said
> > commands within a sub-shell achieves that.

That is not the reason. Code like  { ... } >F  also redirects file
descriptors for the duration of the block but does not create a
subshell. For the Bourne shell freaks,  exec 3>&1 >F; ...; exec >&3 3>&-

One of the reasons is job control. To keep things sane, all processes in
a job should be in the same process group. Executing part of the job in
the main shell process requires special effort to make sure tty
input/output/control works correctly and to handle ^Z, such as by
forking when ^Z happens (which may be unexpected).

Also, the Bourne shell has always executed all elements of pipelines in
a subshell and many shells have followed it.

-- 
Jilles Tjoelker


More information about the freebsd-questions mailing list