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.

Four hard drivers sticking out of a rack-mount server that’s being used as a NAS.

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.

synology nas

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.

Article image

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.

Simple example of starting a subshell in Bash

There is an easier way.

You may think about it like global variables in other coding languages.

Such variables could be consideredglobalalso.

Exporting of a variable

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.

Shows the stability of the export property of a 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.

One cannot remove the export property from a variable from within a subshell if that property was set by the master/parent shell

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.

The parent/master shell can remove the export property from the variable

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.

Using export -p to print exported variables

We also saw a gotcha which can arise if you reuse variable names.Enjoy Exporting!