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

Solution 1:

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

Solution 2:

A few good options. First, my favorite:

screen -x -R

That will attach to the first screen session available (sharing if another connection is connected), and if there are no screen sessions at all, start a new one.

screen -d -RR

Docs for that say "Reattach a session and if necessary detach or create it. Use the first session if more than one session is available." Basically, the double-R makes it look for the first session to attach to.

screen -D -RR

"Attach here and now. Whatever that means, just do it." Will detach and remotely logout any other attached sessions and attach to the first session it can. Basically, does whatever it needs to do to attach to an existing session, and creates a new one if there's nothing there.

The very first (-x -R) is the least likely to cause problems (won't detach your other connection) but just plain always attaches to something if there's anything to attach to and creates something if there's nothing to attach to.

Solution 3:

I use

screen -dRRS sessname

I don't want my entire login on the other shell dropped, like -D does, and I definitely don't want the multi-attach mode of -x.