How can I tell whether I'm in a screen?

后端 未结 9 1699
悲哀的现实
悲哀的现实 2020-12-07 18:11

When using screen in linux, how can I tell if I\'m in a screen or not? I could do exit and I\'ll exit a screen if I was in one, but if I wasn\'t, then I\'ll end

9条回答
  •  -上瘾入骨i
    2020-12-07 19:01

    The problem with most of the above answers is that we might be in a subshell of an attached screen session. Or we might be opening a shell to a remote host from within a screen session. In the former case, we can walk the process tree parentage and match for the screen program name. In the latter case, most of the time, we can check the TERM variable for something like screen*.

    My answer os similar to /u/Parthian-Shot but not so dependent on the pstree utility; the options he use are not available to me. On the other hand, my implementation is still Linux-dependent: for non-Linux systems, one must tweak the ps command; for systems with older shells that don't support arrays, you'll have yet more work-arounds. But anyway:

    ps_walk_parents() {
      local tmp
      local ppid=$PPID
      while [[ $ppid != 1 ]]; do
        tmp=($( ps -o ppid,comm -p $ppid ))
        ppid=${tmp[0]}  # grab parent pid
        echo ${tmp[1]}  # output corresponding command name
      done
    }
    if [[ "$TERM" =~ screen* ]] || ps_walk_parents |grep -qxi screen ; then
      # we are in a screen terminal 
    fi
    

    We could optimize our function a bit to stop searching if/when a process parent matches the target command name ("screen"), but in general, the function will only hit 2 to 3 iterations. Presumably you want to put this code in some startup initialization such as .bashrc or .profile or something, so again, not worth optimizing.

提交回复
热议问题