Let us say it frankly: TMUX is a great console tool!

TMUX is a terminal multiplexer, allowing a user to access multiple separate terminal sessions inside a single terminal window or remote terminal session: like GNU Screen, but with more features and distributed under a BSD-like.

One of the most used feature of terminal multiplexers is "persistence", that allows the user to start applications from one computer, and then reconnect from a different computer and continue using the same application without having to restart it.

The process of re-attach usually is manual: once reconnected, the user needs to restart tmux and re-attach the session.
I think could be really useful automatize this operation, so i want to share this simple code snippet, that could be appended to bash configuration file (.bashrc):

if [[ "$TMUX" == "" ]] &&
        [[ "$SSH_CONNECTION" != "" ]]; then
    WHOAMI=$(whoami)
    if tmux has-session -t $WHOAMI 2>/dev/null; then
    tmux -2 attach-session -t $WHOAMI
    else
        tmux -2 new-session -s $WHOAMI
    fi
fi

The script simply attempts to discover a detached session and attach it, else create a new session.

That's All!


References and further readings