Ubuntu – How to check if screen session is running

bashgnu-screen

Is there any way to check if a screen session is running in bash?
For example:

if [screen is running]
  then
    screen -r          #if session is running then resume the session
  else
    screen "command"   #else start a new session
fi

Best Answer

Take advantage of the PPID (Parent PID) environment variable, and start with

$ ps -fp$PPID
UID        PID  PPID  C STIME TTY          TIME CMD
w3       19305 19304  0 00:00 ?        00:00:00 SCREEN
+w3@aardvark:~(0)$ 

or,

ps -fp$PPID | head -n 2 | tail -n 1 | egrep -q SCREEN
screen_is_running=$((1 - ${PIPESTATUS[-1]}))
# screen_is_running == 1 for yes, 0 for No, -1 for egrep error

Of course, this won't work if you've spawned, exec'ed, nohup'd or something, and made your $PPID not SCREEN.

If that's the case, you could build something with pgrep, pstree, egrep that could follow the $PPID chain back (stop when $PPID is 1).