Sometime when you are accessing your server via ssh, you might face the situation when because of some network issue your connection to server is gone? This happens most of the time.

Not loosing work progress

To save your work or for not loosing any track on the server, you can start using tmux on server. It’s a terminal multiplexer, it enables a number of terminals to be created, accessed, and controlled from a single screen. tmux may be detached from a screen and continue running in the background, then later reattached. Also you can customize it by placing .tmux.conf file inside your home directory. A sample configuration, you can see here.

But when you’ll start using this one more issue you might face. Suppose you’re logged in to the server and you are using tmux, and now you are happy that even if your Internet is gone your progress will not get affected. BUT WAIT, here is one more issue that - when you start tmux session it clears your screen and you can’t see your previous commands or any information you need from previous commands.

Re-connecting to server after disconnection

Here is an article which explains how without using tmux also you can track your command usages. But one more solution to this issue is available. You can kill current stuck ssh session and you can access your history. To do this you don’t need to run kill command, but basically press ~ + . followed by an Enter.

There are bunch of things you can do here, to see the help press ~ + ? followed by Enter. And you will see result like this-

Supported escape sequences:
 ~.   - terminate connection (and any multiplexed sessions)
 ~B   - send a BREAK to the remote system
 ~C   - open a command line
 ~R   - request rekey
 ~V/v - decrease/increase verbosity (LogLevel)
 ~^Z  - suspend ssh
 ~#   - list forwarded connections
 ~&   - background ssh (when waiting for connections to terminate)
 ~?   - this message
 ~~   - send the escape character by typing it twice
(Note that escapes are only recognized immediately after newline.)

Alternative solution

Open file /etc/ssh/ssh_config in your favourite text editor and add below lines-

Host *
ServerAliveInterval 120

This will send a keepalive message to the server on each 120 seconds. You could set either ServerAliveInterval in /etc/ssh/ssh_config of the client machine or ClientAliveInterval in /etc/ssh/sshd_config of the server machine. Try reducing the interval if you are still getting the error.

Caution when you’re using tmux

Now here you stay on the same session and you can see history. The best approach I think is to work with tmux on server but remember don’t run any costly process in tmux session, because when you detach session it’ll not kill the running process.