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?
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.
printf $"var does%${var+.} s exist%c\n" \ not ! ...will tell you either way.
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.
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.)
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]#
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With