2

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
3

By reading man screen you find the COMMAND LINE OPTIONS:

COMMAND-LINE OPTIONS
       Screen has the following command-line options:

    ...snip...

       -d -r   Reattach a session and if necessary detach it first.

       -d -R   Reattach a session and if necessary detach or even create it first.

       -d -RR  Reattach a session and if necessary detach or create it. Use the first session if more than one session is available.

       -D -r   Reattach a session. If necessary detach and logout remotely first.

       -D -R   Attach  here  and now. In detail this means: If a session is running, then reattach. If necessary detach and logout remotely first.  If it was not running create it and notify
               the user. This is the author's favorite.

       -D -RR  Attach here and now. Whatever that means, just do it.

            Note: It is always a good idea to check the status of your sessions by means of "screen -list".

Surely one of these would do what you want without the variable.

0
3

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).

3
  • Have a look at my updated question @waltinator – Hazzdood Sep 10 '16 at 5:52
  • oops, I didn't put the var in quotes – Hazzdood Sep 10 '16 at 9:52
  • If you don't care if screen is uyour parent process, a simple pgrep screen will tell you if screen is running anywhere on your system. – waltinator Sep 10 '16 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.