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

gnu-screen

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?

Best Answer

Try using screen -RR.

Example:

$ 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
Related Question