Access parent shell variable in a subshell

In this article, we cover how to access the parent shell variable in a subshell. A subshell can inherit only limited features from there parent shell which include environment variables. But, not the variables we declare in the shell itself.

Let’s understand it with the help of an example. Declare a variable in the parent shell, x:

x="Hello World!"

And, open an instance of the shell i.e. subshell through the following command:


and, try to access the shell variable:

echo $x

Clearly, it couldn’t come up with anything. As a subshell can’t access shell variables. Use the export command-line utility to have access to such variables in the subshell as well.

Access parent shell variable in a subshell

By default, the shell variables can’t be accessed from the subshell. But, the export command-line utility makes the shell variable accessible through the subshell.

Continuing with the above example. Instead of declaring a variable the traditional way. Use it with the help of the export command-line utility. For instance,

export x="Hello World!"

And, open a subshell through the command:


And, this time around we should be able to access the variable x:

echo $x

It should return with:

Hello World!

In conclusion, we have covered how to access the parent shell variable in a subshell.

Additional Info:

In case we have declared a shell variable and wouldn’t wish to use it later in a subshell. Then, we have to use the unset command-line utility. As the name itself suggests, it is used to unset the shell variable values.

We continue with the above example. At this stage, we are in a subshell and have already exported variable x through the export command-line utility.

Now, to unset the values of variable x in the subshell, use:

unset x

Now, try executing the following command again:

echo $x

It wouldn’t have anything. It is worth mentioning here that, it won’t affect value stored in variable x in other subshells as well as the parent shell.

Similar Posts