Vamos ver o que o manual do Bash diz ( 3.7 .3 Ambiente de execução de comandos )
The shell has an execution environment, which consists of the following:
- shell parameters that are set by variable assignment or with set or inherited from the shell’s parent in the environment
- shell functions defined during execution or inherited from the shell’s parent in the environment
Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment [...]
Changes made to the subshell environment cannot affect the shell’s execution environment.
Em 3.2.2 Pipelines , também é dito p>
Each command in a pipeline is executed in its own subshell
(Claro que isso só se aplica a pipelines multi-comando)
Assim, as partes de um pipeline, bem como outros subshells, obtêm cópias de todas as variáveis do shell, mas quaisquer alterações nelas não são visíveis para o exterior concha.
Com outros comandos, você ainda precisa export
:
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, along with variables exported for the command, passed in the environment
Alimento para o pensamento: o que isso imprime?
bash -c 'f() { echo "$a $b"; }; a=1; b=1; (b=2; f); f'