Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know if I'm running a nested shell?

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?

like image 473
Mansoor Siddiqui Avatar asked Dec 22 '10 16:12

Mansoor Siddiqui


People also ask

How do you check which shell am I running?

How to check which shell am I using: Use the following Linux or Unix commands: ps -p $$ – Display your current shell name reliably. echo "$SHELL" – Print the shell for the current user but not necessarily the shell that is running at the movement.

How do I check if a variable exists in shell?

printf $"var does%${var+.} s exist%c\n" \ not ! ...will tell you either way.

What nested commands?

If you are working in the command bar, you can use another command from within a command, called nesting. To use a command inside an active command, type an apostrophe before you type the command, such as 'circle, 'line, or 'pyramid. You can nest commands indefinitely in progeCAD.

How do you find Subshells?

One quick way to see if you're in a subshell or not is to echo $0 . If it's the toplevel shell, it will probably start with a dash. (This is true at least for bash, and the dash means that it's a so-called login shell.)


2 Answers

The $SHLVL variable tracks your shell nesting level:

$ echo $SHLVL 1 $ bash $ echo $SHLVL 2 $ exit $ echo $SHLVL 1 

As an alternative to spawning sub-shells you could push and pop directories from the stack and stay in the same shell:

[root@localhost /old/dir]# pushd /new/dir /new/dir /old/dir [root@localhost /new/dir]# popd /old/dir [root@localhost /old/dir]# 
like image 196
John Kugelman Avatar answered Sep 29 '22 08:09

John Kugelman


Here is a simplified version of part of my prompt:

PS1='$(((SHLVL>1))&&echo $SHLVL)\$ ' 

If I'm not in a nested shell, it doesn't add anything extra, but it shows the depth if I'm in any level of nesting.

like image 31
Dennis Williamson Avatar answered Sep 29 '22 07:09

Dennis Williamson