Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm wondering whether I've called the shell recursively, is there an easy way to find out? Is any solution specific to the shell? I'm using bash.

share|improve this question
up vote 18 down vote accepted
echo $SHLVL

From the bash manpage:

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

share|improve this answer
Ah, there it is! – altCognito Jun 15 '09 at 18:47
So I guess checking the parent process ID recursively would be a waste of time, eh? – sangretu Jun 15 '09 at 18:50
Checking the parent process does have the advantage that it'll work for any shell. – brian-brazil Jun 15 '09 at 18:52

One way is to use pstree:

$ pstree -h
│      └─sshd───sshd───bash───bash───bash───bash
share|improve this answer
echo $SHLVL

This will catch if you do something like:

[sharpestmarble@sandbox ~]$ bash

Although that won't catch something like if you SSH into localhost.

[sharpestmarble@sandbox ~]$ ssh localhost
share|improve this answer

Also useful: $BASH_SUBSHELL

$ echo $SHLVL
$ (echo $SHLVL)
$ ( (echo $BASH_SUBSHELL) )
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.