Both subshell and bash -c
contexts can access exported variables. To export a variable, one declares the variable as exported (e.g., declare -x VAR
) or specifically exports it (export VAR
). Your example, it seems, does not export x
.
More of the parent context is inherited by subshells (e.g., ( ... )
), than are by specific command executions (e.g., bash -c ...
).
For example, the following items are inherited by subshells:
- Current working directory; e.g., as set with
cd
, pushd
, and/or popd
- Directory stack (
DIRSTACK
); e.g., as affected by cd
, pushd
, popd
- File creation mask; e.g., as set with
umask
- File handles/descriptors; e.g., initially and as affected by
exec
redirections
- Settings; e.g., as affected by
set
, shopt
, and alias
- Shell variables and functions; e.g., as set with
declare
and =
- Exported variables and functions; e.g., as declared with
declare -x
or exported with export
- Signal traps for
ERR
; e.g., as set with trap ... ERR
- Certain special shell parameters; e.g.,
PPID
For example, the following items are inherited by command executions (w. bash -c
):
- Current working directory; e.g., as set with
cd
, pushd
, and/or popd
- File creation mask; e.g., as set with
umask
- File handles/descriptors; e.g., initially and as affected by
exec
redirections
- Exported variables and functions; e.g., as declared with
declare -x
or exported with export
For additional detail, check out the Bash manpage, starting with the COMMAND EXECUTION ENVIRONMENT section.
Note: Each command in a pipeline executes in dedicated processes/subshells. With lastpipe
enabled, the final pipeline command may run within the outer shell process.
Note: Other than when a command list is fully backgrounded with a trailing &
, command lists are executed within the current shell process. When backgrounded, command lists are executed in a dedicated process/subshell.