Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question

migrated from Apr 9 '13 at 1:55

This question came from our site for professional and enthusiast programmers.

up vote 11 down vote accepted

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).

share|improve this answer
Thanks! I was reading around and I was under the impression that I would need exec screen -R. Glad this worked – Ronald Dregan Apr 9 '13 at 3:48

If I understand your need, you should try :

if $(screen -ls | grep -q pts); then screen -x; else screen -R; fi

It will create only one screen session, otherwise it will reconnect to the existing one in a multi-windows fashion ( even if you have multiple ssh session, you will end up to the same screen session )

share|improve this answer

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.

share|improve this answer
+1 - like this better than the screen -ls test that Tony mentioned – cwd Mar 22 at 20:53

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

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.