The first thing I install on every UNIX machine on which I have enough administrative rights is tmux (terminal multiplexor) - I feel uncomfortable to connect to it via SSH otherwise. For example, you could encounter some problems with your Internet connection - any sudden disconnect might disrupt a lengthy operation like backup which might have been initiated from within the remote terminal session. I want my remote session to be persistent.

I used to have a habit to start a tmux session right after I have connected to a remote server via SSH. Recently I realised that this action can be automatised. I ended up with the following code-snippet which might be placed into your shell initialisation file (e.g. .bashrc for bash):

# Attach to the tmux session on login via SSH.
if [ ! -z "$SSH_CLIENT" ] && [ -z "$DESKTOP_SESSION" -a -z "$TMUX" ] ; then
    tmux attach -t remote || tmux new -s remote
fi

The above-mentioned snippet automatically tries to connect to an existing tmux session named remote or start a new one when logged-in via SSH. It contains some additional checks, which should be discussed:

  1. There is a check for empty DESKTOP_SESSION environmental variable to avoid connecting to the tmux session from within remote X Session initiated over SSH;
  2. There is a check for empty TMUX environmental variable to avoid connecting to the tmux session recursively.

I believe that being able to automatically reconnect to an existing terminal session is very convenient. I hope you will find it useful too.