11

Say I start a bash shell,
...and then another bash session from within that shell,
...and then another bash session from within that session,
...and then another bash session from within that session,
...(times N) etc

To exit all N sessions I have to type exit N times.

How do I find out how deep I am nested from within any given bash session?

Ideally I'm looking for some environment variable similar to $STY for screen sessions.

tetris11
  • 355

1 Answers1

18

Use SHLVL. From man bash :

SHLVL  Incremented by one each time an instance of bash is started.

Example :

$ echo $SHLVL
1
$ bash
$ echo $SHLVL
2
$ bash
$ echo $SHLVL
3
heemayl
  • 56,300
  • This is good, but I've noticed a slight problem with my setup: - my .xinitrc starts one shell as a regular process, but another using exec (so that when this terminal closes, the entire XSession ends). $SHLVL produces two different numbers for these terminals. Is there an environment variable that is more shell-specific? – tetris11 Aug 06 '15 at 13:56
  • $BASH_SUBSHELL looked promising, but doesn't deliver. – tetris11 Aug 06 '15 at 14:00
  • 1
    @tetris11Yeah..thats how SHLVL works..check this solution if it fits.. – heemayl Aug 06 '15 at 14:12
  • 1
    Ah, of course - I can manually set SHLVL=0 in ~/.xinitrc. Brilliant, thanks – tetris11 Aug 06 '15 at 14:32