Reattach or create a named screen session? (or persistent screen sessions)

gnu-screen

Basically I have a remote screen session, which I wish to automatically reattach to.. Currently I'm doing this by with the following command (as an iTerm bookmark, or an alias)

ssh host -t screen -x thesessionname

This works fine, but if the session dies for whatever reason, I'd like it to be recreated when I next connect. The -R flag for screen is almost perfect:

ssh host -t screen -R -S thesessionname

..but if the session is already attached, a second session gets made (as -R simple looks for the first detached session, if none are found it creates a new one)

Is there a way to make the -R flag look for attached sessions also, and only create a new one if thesessionname doesn't exist?

If this is not easily doable, how could I automatically recreate the screen session when it dies? Perhaps a script run via cron that looks for the named session, creating it should it not exist?

Best Answer

Tell screen to be a bit more persistent about trying:

-D -R
    Attach here and now. In detail this means: If a session is run-
    ning,  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.

So combine the two and you should have your solution ("-DR" is equivalent to "-D -R"):

screen -DR <yoursession> 

Additionally and useful to know, you can view running sessions with:

screen -ls