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.
Asked
Active
Viewed 405 times
4 Answers
19
echo $SHLVL
From the bash manpage:
SHLVL Incremented by one each time an instance of bash is started.

brian-brazil
- 3,952
- 1
- 22
- 16
-
Ah, there it is! – cgp Jun 15 '09 at 18:47
-
2So I guess checking the parent process ID recursively would be a waste of time, eh? – sangretu Jun 15 '09 at 18:50
-
1Checking the parent process does have the advantage that it'll work for any shell. – brian-brazil Jun 15 '09 at 18:52
6
One way is to use pstree:
$ pstree -h
[...]
├─sshd─┬─sshd───sshd───bash───bash───bash───bash───bash───pstree
│ └─sshd───sshd───bash───bash───bash───bash
[...]

rkthkr
- 8,618
- 28
- 38
2
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

Kevin M
- 2,312
- 1
- 16
- 21
1
Also useful: $BASH_SUBSHELL
$ echo $SHLVL
1
$ (echo $SHLVL)
1
$ echo $BASH_SUBSHELL
0
$ (echo $BASH_SUBSHELL)
1
$ ( (echo $BASH_SUBSHELL) )
2

Dennis Williamson
- 62,149
- 16
- 116
- 151