When using a *nix shell (usually bash), I often spawn a sub-shell with which I can take care of a small task (usually in another directory), then exit out of to resume the session of the parent shell.
Once in a while, I'll lose track of whether I'm running a nested shell, or in my top-level shell, and I'll accidentally spawn an additional sub-shell or exit out of the top-level shell by mistake.
Is there a simple way to determine whether I'm running in a nested shell? Or am I going about my problem (by spawning sub-shells) in a completely wrong way?
pstree -s $$
is quite useful to see your depth.ptree $$
will also show you how many levels deep you areThe environment variable
$SHLVL
contains the shell "depth".The shell depth can also be determined using
pstree
(version 23 and above):I've found the second way to be more robust than the first whose value was reset when using
sudo
or became unreliable withenv -i
.None of them can correctly deal with
su
.The information can be made available in your prompt:
The
| tail +2
is there to remove one line from thegrep
output. Since we are using a pipeline inside a "$(...)
" command substitution, the shell needs to invoke a sub-shell, so pstree report it and grep detects one moresh-
level.In debian-based distributions,
pstree
is part of the packagepsmisc
. It might not be installed by default on non-desktop distributions.If you running inside sub-shell following code will yield 2:
Otherwise, it will yield 1.
EDIT Ok, it's not so robust approach as was pointed out in comments :)
Another thing to try is
will yield 'bash' if you in sub-shell.
The
$SHLVL
variable tracks your shell nesting level:As an alternative to spawning sub-shells you could push and pop directories from the stack and stay in the same shell:
Look at
$0
: if it starts with a minus-
, you're in the login shell.