How to make screen -R attach to the youngest detached session?

I’m using screen on debian lenny, and I would like to use the -R option. From man screen:

   -R   attempts  to  resume  the  youngest  (in  terms  of creation time)
        detached screen session it finds.  If successful, all  other  com‐
        mand-line  options  are  ignored.   If no detached session exists,
        starts a new session using the specified options, just  as  if  -R
        had  not been specified.

However, when I run screen -R it does not actually attach to the youngest detached session. Instead, it complains that there are “several suitable screens” and that I need to choose one of them.

Am I missing something? How do I make this work as advertised?

Asked By: Wim Coenen


Try using screen -RR.


$ screen -ls
There are screens on:
    5958.pts-3.sys01    (08/26/2010 11:40:43 PM)    (Detached)
    5850.pts-1.sys01    (08/26/2010 11:40:35 PM)    (Detached)
2 Sockets in /var/run/screen/S-sdn.

Note that screen 5958 is the youngest. Using screen -RR connects to screen 5958. The -RR options is somewhat further explained in the documentation for -d -RR.

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

Another trick I often use is to use -S to give the screen a tag/label. Then you can reattach using that tag without having to remember what was happening in each screen if the list gets unwieldy.

Example (Launch screens for vim and curl):

$ screen -dm -S curl
$ screen -dm -S vim 
$ screen -list

There are screens on:  
    11292.vim       (08/27/2010 12:02:53 AM)        (Detached)
    11273.curl      (08/27/2010 12:01:42 AM)        (Detached)

Note: The -dm option was just used to start a detached screen

And then, at a later date, you can easily reconnect using the tag curl.

# screen -R curl
Answered By: David Narayan

I use screen -R in gnome-terminal and, as you said, if 2 sessions are running at the same time, then gnome-terminal quits immediately.

I solved it by running

sh -c "screen -R || screen -D -RR"

this works just as you expect.

Answered By: user6058
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.