Ssh – alias to detach screen when I exit (and kill ssh)

gnu-screenssh

I auto start gnu screen when I ssh into one on my own servers. When I am done, I have to d to detach. Then exit to quit ssh. This means that when I ssh into the server again at some point in time, I can continue where I left off.

Can I create a alias (for instance) that will (from within screen) detach and drop ssh?

Best Answer

Starting screen when logging in on the remote host (executed on your local machine):

ssh -t user@host screen

In the screen session, on the remote host, to detach and log out (which would end the SSH session unless you are using a persistent connection using a control socket (i.e. using the ControlMaster setting with ControlPersist in ~/.ssh/config)):

screen -d

Later, to log in and re-attach:

ssh -t user@host screen -r

Note that you have to use -t with ssh, forcing pseudo-terminal allocation, to start screen in this way.

The alias on the remote host would be for screen -d, maybe detach='screen -d' or something similar.

On the local host, you could have a section in your ~/.ssh/config file saying

Host *-screen
    RequestTTY force
    RemoteCommand screen -d -R

Host myhost myhost-screen
    HostName myhost.somedomain.example.com
    User myname

Then, whenever you use

ssh myhost-screen

a screen session would be created (or re-attached to) on the specified host, while

ssh myhost

would not use screen.

Note: RemoteCommand was added in OpenSSH 7.6 (2017-10-03).


For tmux:

  • Use tmux new-session -A -s "%n" in ~/.ssh/config instead of screen -d -R.
  • Use prefixd or tmux detach-client or tmux detach to detach.
Related Question