It is exactly in these types of situations that exporting shell variables becomes of interest.
What Is aBash subshell?
If the master process/shell terminates, so will the subshell running within it.
We can verify the same by checking what sort of processes are live.
First, we discover the PID (process ID) of our current (sub-)shell.
We can do so by inspecting the$$variable withecho.
The PID is 362827.
This allows us to backtrack as far as we can or like to go.
Exporting Variables to Subshells
There are many ways to create a subshell.
One way is to simply start a subshell as shown above by typingbashand executing further command line based commands.
Finally, one can start a subshell simply by placing a process into background.
To learn more about background process management, seeBash Background Process Management.
There is an easier way.
You may think about it like global variables in other coding languages.
Such variables could be consideredglobalalso.
The syntax for the export command is very simple.
We also see how the variableBhas not transferred to the subshell, as it was defined without usingexport.
The export property is a specific property which can be turned on and off for a given variable.
It is easily turned on by using theexportcommand prefix when defining the variable.
Once such a property is set, it remains active.
The export property can also be removed from/turned off for a variable, by using the-noption toexport.
still from within the active subshell).
We try and remove theexportproperty from theDvariable, and subsequently exit the subshell usingexit.
This is alike to other Bash coding methods: the subshell cannot affect the master/main shell.
you’ve got the option to also runexport -pto see all export variables.
The variables you exported are likely near the top of this list.
We looked at various ways to export variables, as well as a method to clear theexportproperty from variables.
We also saw a gotcha which can arise if you reuse variable names.Enjoy Exporting!