Subshell level in Bash

In this article, we cover the subshell level in Bash. There is an internal variable: SHLVL which helps us understand whether our process is currently running in a subshell or not.

But, before that a bit on subshells. A subshell is mainly an instance of the parent shell. If we work with subshells, it becomes necessary to identify the subshell level. For instance, If we have declared a variable for the parent shell. That won’t work with the subshell. We would still be able to access global variables though.

Understand it with the help of an example:

Open a Shell, and declare the following variable:

x="Hello World!"

And, do:

echo $x

It would get the following in the standard output:

Hello World!

Now, open an instance of the Shell by running the following command:

bash

And, try the following again:

echo $x

It would return with nothing.

It is worth mentioning here that, at this stage, you may not even realize that you are already working with a subshell. That is where the SHLVL variable is quite useful.

Subshell level in Bash

So, now we move to the next part i.e. how to identify the subshell level in Bash? SHLVL isn’t just like any other variable. It is an environment variable that can even be accessed through subshells as well.

When we launch a shell, running the following command would get us 1 in the output:

echo $SHLVL

1 here shows that we are working with the parent shell. And, as we open more instances (or, subshells) of the parent shell. The value of SHLVL increases by 1 for every subshell so opened.

Now, run the following command:

bash

It opens a subshell. Again do:

echo $SHLVL

This time around we should get 2 in the standard output. If we repeat the same process, then we get 3. And, that is how it will be for more subshells to open.

In conclusion, we have covered here how to identify subshell levels in Bash.

Similar Posts