You need screen -R -d
to both automatically attach to an existing session if one exist and create a session otherwise.
Make sure you only do this on interactive shells. Bash sources ~/.bashrc
even for non-interactive shells when its parent process is rshd or sshd (this is mentioned in the documentation, but it's easy to miss). You can tell a shell is interactive because $-
contains i
.
case $- in
*i*) screen -Rd;;
esac
This won't easily let you run different screen sessions in different terminals.
You'll need to detach from screen, then exit the parent shell to log out. This can be resolved by using exec screen
instead of screen
.
If you start a shell other than a login shell, you'll be put into screen, which is not what you'd want most of the time. I would at least restrict this to when you're running directly in an interactive ssh session, with something like the following in your ~/.bash_profile
:
case "/$(ps -p $PPID -o comm=)" in
*/sshd) screen -R -d;;
esac
Be careful when you do complex things with your .bashrc
as an error that causes the shell to exit would make it difficult to log in.
What I recommend is to not modify your shell initialization files on the server, but instead run screen explicitly from the client, as in
ssh -t host.example.com screen -R -d
(You would probably create a shell alias or desktop environment shortcut on the client.) That way you can easily choose not to run screen, specify an alternate session name and so on.
Isn't it better for ssh to run
screen -D -R
or evenscreen -D -RR
? – niutech – 2016-01-29T18:47:34.297Perfect. Should be in the man page. – marcusw – 2010-12-24T02:16:06.317