automatically start screen upon ssh login

I have been reading about how to automatically start a screen when I ssh to a remote server. I would like a simple one-liner to add to my .bash_profile to start screen when I ssh in, and NOT exit my remote connection when I detach the screen.

I have been looking into exec screen and pretty much every combination of -d, -r, -D and -R and cannot figure out what flags I need.

Ideally I would type ssh whatever and be logged into the server in a new screen or it can reattach an old screen, I would kind of like to know how to do both to see which I like better. Then I can either type Ctrl ad or Ctrl d and have it bring me back to the normal ssh login for that server (where you would see the motd). From there I can screen -r back into whatever screen I want, or hit Ctrl d again to log out.


Solution 1:

A simple screen -R should do the trick.

To verify this, I added screen -R to my .bash_profile on a remote server, logged in, detached from screen, and was dropped back to a normal shell prompt on the remote server. Verified with .bashrc as well. Subsequent logins yielded the expected result (re-attach to screen session).

Solution 2:

screen -RR will reattach to the first available session or create one if necessary.

Solution 3:

I had issues with 40 cascading screen sessions being created with some of the solutions when starting a new window or screen session. I was able to eliminate the cascading screen and create a new session if one didn't exist with this:

if [ -z "$STY" ]; then screen -R; fi

It tests whether you're in a screen session and runs screen -R if you aren't. Without the test you get the "Attaching from inside of screen?" warning from screen each time you create a new screen window.