Bash Internal variables $SHLVL

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

When the bash command is executed a new shell is opened. The $SHLVL environment variable holds the number of shell levels the current shell is running on top of.

In a new terminal window, executing the following command will produce different results based on the Linux distribution in use.

echo $SHLVL

Using Fedora 25, the output is "3". This indicates, that when opening a new shell, an initial bash command executes and performs a task. The initial bash command executes a child process (another bash command) which, in turn, executes a final bash command to open the new shell. When the new shell opens, it is running as a child process of 2 other shell processes, hence the output of "3".

In the following example (given the user is running Fedora 25), the output of $SHLVL in a new shell will be set to "3". As each bash command is executed, $SHLVL increments by one.

~> $ echo $SHLVL
3
~> $ bash
~> $ echo $SHLVL
4
~> $ bash
~> $ echo $SHLVL
5

One can see that executing the 'bash' command (or executing a bash script) opens a new shell. In comparison, sourcing a script runs the code in the current shell.

test1.sh

#!/usr/bin/env bash
echo "Hello from test1.sh. My shell level is $SHLVL"
source "test2.sh"

test2.sh

#!/usr/bin/env bash
echo "Hello from test2.sh. My shell level is $SHLVL"

run.sh

#!/usr/bin/env bash
echo "Hello from run.sh. My shell level is $SHLVL"
./test1.sh

Execute:

chmod +x test1.sh && chmod +x run.sh
./run.sh

Output:

Hello from run.sh. My shell level is 4
Hello from test1.sh. My shell level is 5
Hello from test2.sh. My shell level is 5


Got any Bash Question?