Subshell
Subshell
The definition of Subshell in some books or materials is unclear, and the explanations often contradict each other, making it difficult to understand. Therefore, to avoid this semantic and logical problem, we will not provide its definition (it is recommended to refer to the official BASH manual), nor will we use the translation “sub Shell”, but rather understand its definition from its actual behavior. The variables listed below are closely related to the concept of Subshell.
Bash Reference Manual
Bash Reference Manual
BASH_SUBSHELL
Shell variable, not an environment variable, as explained in the official manual.
You can also use the man command, which may have some differences in content.
SHLVL
Environment variable, as explained in the official manual.
Using the man command.
This value starts from 1.
Command Grouping
Full name Command Grouping, Bash provides two methods for creating command grouping.
Parentheses: ()
This method creates a Subshell environment to handle command grouping.
We can draw the following conclusions.
- BASH_SUBSHELL: Increases by 1 for each Subshell created.
- SHLVL: Does not change regardless of how many Subshells are created.
Braces:
This method does not create a Subshell, and command grouping is processed in the context of the current Shell. In syntax, the space between the braces and the command cannot be omitted, and the semicolon at the end of each command is also required.
Shell PID
You can view the Shell’s PID through BASHPID or $$
, but they are different.
BASHPID
Shell variable, not an environment variable, as explained in the official manual.
Using ()
to view BASHPID.
It can be seen that BASHPID outputs the PID of the Subshell.
Special Parameter $$
Official explanation.
In a Subshell, $$
represents the PID of the invoking shell.
It can be seen that, regardless of how many Subshells there are, $$
always represents the PID of the top-level Bash.
Creating a Bash Instance
In Bash, typing bash
creates a brand new Bash instance.
At this point, let’s observe the variables mentioned above again.
- BASH_SUBSHELL: No change.
- SHLVL: From 1 -> 2.
- BASHPID: The PID of the new Bash instance.
- $$: The PID of the new Bash instance.
If we say that this way of creating Bash is also a Subshell, the semantics and behavior would be contradictory.