The $SHLVL variable tells you how many deep shells you have. If this bothers you, you should start from the beginning.
What is a shell?
Shell accepts commands and issues those commands to the main operating system for execution. On most Linux systems, the shell program is called bash (a shell of Bourne Again), but there are others, including shell C (tcsh) and shell KORN (ksh).
How to access the Linux shell
Typically, the user as a user interacts with the shell program through program terminal emulation, such as XTerm , console or gnome-terminal.
If you start a window manager such as openbox, or a desktop environment such as GNOME or KDE you will find the terminal emulator from the menu or from the dash. On many systems, the keyboard shortcut CTRL+ALT+T opens a terminal window.
Alternatively, you can switch to another TTY (teletypewriter) that provides direct shell access. You can do this by clicking CTRL+ALT+F1 or CTRL+ALT+F2 .
What is a shell level?
When you run a command in a shell, it runs at the shell level. Inside a shell, you can open another shell, making it a subshell of the shell that opened it. Therefore, the parent shell is considered a level 1 shell, and the child shell is considered a level 2 shell.
How to display shell level
To determine which shell level you are working in, use the $SHLVL variable. To see the shell level you are currently working in, type the following:
echo $ SHLVL
When you run the above command in a terminal window, the result returned is 2. If, however, you run the same command using a tty, then the result is 1. A tty does not start a desktop environment and is a level 1 shell.
Why is it so? The desktop environment you are using runs on top of a shell. This shell is level 1. Any terminal window you open from this desktop environment is a child of the shell that opened the desktop environment. Therefore, the shell level cannot start with any number other than 2.
How to create subshells
The easiest way to test the concept of shells and subshells is as follows. Open a terminal window, then type the following:
echo $ SHLVL
When you run this command from a terminal window, the minimum shell level is 2.
Enter the following in a terminal window:
The sh command starts an interactive shell. This means you are using a shell within a shell, or a subshell.
If you enter this again:
echo $ SHLVL
You can see that the shell level is set to 3. Running the sh command from a subshell opens a subshell of the subshell, so the shell level is at level 4.
Why is the Shell level important?
The shell level is important when you think about the scope of variables in your scripts. For a simple example:
собака = мейзи
эхо $ собака
If you run the above command in a shell, terminal window the word will appear Maisie .
To open a new shell, type the following: