简体   繁体   中英

If bash pipeline commands run in subshell, why echo command can access the non-exported variables?

Bash manual says "Each command in a pipeline is executed as a separate process (ie, in a subshell)". I test two simple commands.

Scene 1

cd /home/work
str=hello
echo $str | tee a.log

It outputs:

hello

It seems that echo command is not executed in a subshell, as it can access the non-exported variable $str .

Scene 2

cd /home/work
cd src | pwd
pwd

It outputs:

/home/work

Is looks like cd command is executed in a subshell, as it doesn't affect the working directory of original shello.

Can anyone explain why the behaviors are not consistent?

Can anyone explain why the behaviors are not consistent?

Well, because this is how it was designed. A "subshell" inherits the whole context, not only exported variables.

Bash manual says "Each command in a pipeline is executed as a separate process (ie, in a subshell)"

Bsah manual is available here . The sentence you are mentioning literally has a link to solve the mystery:

Each command in a pipeline is executed in its own subshell, which is a separate process (see Command Execution Environment).

Then you can check the "Command Execution Environment", from it (emphasis mine):

The shell has an execution environment, which consists of the following:

  • ...
  • shell parameters that are set by variable assignment...
  • ...

...

Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment , ....

A subshell has all the environment (well, except traps). On the other hand commands:

When a simple command other than a builtin or shell function is to be executed, it is invoked in a separate execution environment that consists of the following. ....

  • ...
  • shell variables and functions marked for export, ...

If bash pipeline commands run in subshell, why echo command can access the non-exported variables?

Because a subshell inherits the parent environment, including all the non-exported variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM