The problem with most of the above answers is that we may be in a subshell of the connected screen session. Or we can open a shell on a remote host from a screen session. In the first case, we can track the origin of the process tree and match the name of the screen program. In the latter case, most of the time we can check the TERM variable for something like screen* .
My os answer is similar to / u / Parthian -Shot, but not so much dependent on the pstree utility; the options that he uses are not available to me. On the other hand, my implementation is still Linux-dependent: for non-Linux systems, you need to configure the ps command; for systems with old shells that do not support arrays, you will have even more options for work. But anyway:
ps_walk_parents() { local tmp local ppid=$PPID while [[ $ppid != 1 ]]; do tmp=($( ps -o ppid,comm -p $ppid )) ppid=${tmp[0]}
We could optimize our function a bit to stop the search if / when the parent of the process matches the name of the target command ("screen"), but in general the function will perform only 2 to 3 iterations. Presumably you want to put this code in some startup initialization, such as .bashrc or .profile or something else, so you should not optimize.
Otheus Sep 22 '16 at 16:47 2016-09-22 16:47
source share