tmux to manage your server

Today I discovered tmux, a GNU screen-like application. It allows you to keep your console sessions alive and manage multiple shells in the same window. Check out the website to get an idea: tmux.sf.net

What’s really neat about it, is that even if the SSH connection to your server breaks, you can just connect back, “tmux attach”, and you can continue where you left off.

For me, the next step, was to login by default into tmux when connecting to the server. It allows me to run long-running processes like workers and keep an eye on them (until I switch to monit or something else). Here is how I did it.

Basic configuration

Edit your ~/.tmux.conf to:

# Restore sane default shortcut
unbind C-b
set -g prefix C-a
bind C-a send-prefix

# Default session
# make sure to have one, otherwise "tmux attach"
# will fail if there is no session
new

It’s just that Ctrl-A is much more accessible than Ctrl-B on my keyboard, and it’s also the GNU screen default that I learned.

Next, we want to launch “tmux attach” on new connections. For that, edit the ~/.bashrc:

# Make sure you have this line somewhere before
# We don't want to attach tmux on non-interactive connections.
if [[ -n "$PS1" ]]; then

# Add the following line as the last commands of the file
# If $TMUX is not set (set by tmux on sub-shells),
# attach or create a session:
if [ -z "$TMUX" ]; then
  exec tmux attach
fi

That’s it. Now everytime you ssh to your server, your last session will be re-opened. Notice that if you have two connections, you can see the typing of one into the other.

IDEA: It would be nice if a process monitor would have such kind of feature. Just to watch the stdout and stderr and send some signals to the process.

Update: 11 dec. 2010

One of the drawbacks of this approach is that you’re loosing normal terminal behavior. For example the line history is not available to scolling. There must be a command to emulate it, but I don’t know which-one.