[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
why are pipeline commands (allowed to be) executed in subshells?
From: |
Philippe Cerfon |
Subject: |
why are pipeline commands (allowed to be) executed in subshells? |
Date: |
Fri, 25 Nov 2022 18:51:47 +0100 |
Hey.
I noticed that bash (an other shells) seem to execute every command of
a pipeline:
[!] cmd1 [ | cmd2 …]
in separate subshell, but only when there's actually at least one pipe
operator ([!] cmd1 alone is, as per POSIX, also a pipeline).
For example:
n=1
echo foo | { n=2 ;}
echo $n
yields:
1
Or:
n=1
echo foo | { n=2 ;}
echo $n
yields:
1
And:
n=1
{ n=2 ;} | echo $n
echo $n
yields:
1
1
meaning that there is one subshell per command of the pipeline, and
not one for all.
It's clear that any non-built-in command/programs are executed not in
the same shell environment, but why are all shell commands?
Any what in POSIX even allows this?
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html:
- There is no command substitution involved.
- What's said in 2.9.1 Simple Commands about subshells is only about
redirections, when there is no command name.
- 2.9.2 Pipelines says "If the pipeline begins with the reserved word
! and command1 is a subshell command…", but the next sentence clearly
refers to the ( ) grouping command.
- there's no asynchronous list, which would make the commands executed
in subshells
And if the argument were "well it doesn't mandate it but doesn't
forbid it either"; then why is the one element pipeline:
[!] command
e.g. n=2
not executed in a subshell either?
If POSIX would allow that behaviour for pipelines, wouldn't that kill
any assignments?
Or why are AND/OR lists not:
n=1
echo foo && { n=2 ;}
echo $n
yields:
foo
2
and:
n=1
{ n=2; } && { n=$((n+1)) ; echo $n; n=5; }
echo $n
yields:
3
5
Regards,
Philippe
- why are pipeline commands (allowed to be) executed in subshells?,
Philippe Cerfon <=