0

This question is different from In Bash, how can I detect if I'm in a subshell? because it's not shell specific.

Let's say I open a terminal, which is zsh. I can go deep into that like this,

$ echo $$
359648
$ zsh
$ echo $$
359706
$ zsh
$ echo $$
359746
$ exit
$ echo $$
359706
$ exit
$ echo $$
359648

I want the first invocation of zsh to realize that we're already in zsh and to refuse the the creation of a subshell. Realizing that a shell is just a regular program and the notion of a "subshell" is just a basic abstraction when you so happen to spawn the same shell in a parent shell, is this even possible?

  • Is it possible to detect when this condition would be reached?
  • Is it possible to detect when this condition has already occured.

This question is not specific to zsh

AdminBee
  • 22,803
Evan Carroll
  • 30,763
  • 48
  • 183
  • 315
  • 1
    You're not creating a subshell there, you're starting a whole another instance of zsh. A shell is just a regular program, but a subshell is not the same as just starting a new shell, but an independent execution environment that starts as a original environment. In particular, a subshell will see any shell variables set in the main shell, while a new instance of the shell will not. – ilkkachu Mar 05 '23 at 20:30
  • if you want to prevent starting a new shell from e.g. an interactive shell, why not just define a function with the same name? e.g. zsh() { echo sorry; } – ilkkachu Mar 05 '23 at 20:34

1 Answers1

-1

How about something like this

thisshell=$(ps -o comm= -p $$)
if [ $(ps -o comm= -p $(ps -o ppid= -p $$)) == "$thisshell" ]
then
   echo subshell
else
   echo not subshell or different shell
fi
user10489
  • 6,740
  • this seems to have nothing to do with detecting subshells – ilkkachu Mar 05 '23 at 20:35
  • It detects if the current process is a subshell of the parent. – user10489 Mar 05 '23 at 22:28
  • It appears to check if the parent process of the main shell process has the same name as the main shell process. A subshell process (if implemented by forking) and the main shell process likely do have the same name, but $$ gives the PID of the main shell process, not that of the currently running subshell process. – ilkkachu Mar 06 '23 at 07:07
  • If $$ doesn't give the current shell, then the answers to the previous question should work. This case covers ones where those don't work. – user10489 Mar 06 '23 at 12:42