Home » Posts tagged "script"

Tmux scripting

I’ve been using tmux for a while no to manage my terminal sessions. One thing I kept on doing was after starting tmux that I would be manually adding windows, splitting them and issuing commands in each pane such as echoing the contents of log files with tail -f.

I had heard about scripting tmux before but never really looked into it yet, until now. Since I solely use the key bindings I had to figure out how to issue these commands without them. Turns out this is pretty easy and it’s documented in the man page.

Here’s an example of a tmux script I just added to Maximus-Web.

#!/bin/bash
SESSION=$USER

tmux -2 new-session -d -s $SESSION

# Setup a window for tailing log files
tmux new-window -t $SESSION:1 -n 'Logs'
tmux split-window -h
tmux select-pane -t 0
tmux send-keys "tail -f /vagrant/maximus.log" C-m
tmux select-pane -t 1
tmux send-keys "tail -f /vagrant/maximus-worker.log" C-m
tmux split-window -v
tmux resize-pane -D 20
tmux send-keys "tail -f /vagrant/maximus-mojo.log" C-m
# Setup a CoffeeScript compiler/watchdog pane
tmux select-pane -t 0
tmux split-window -v
tmux resize-pane -D 20
tmux send-keys "coffee -o /vagrant/root/static/js/ -cw /vagrant/root/coffee/" C-m

# Setup a MySQL window
tmux new-window -t $SESSION:2 -n 'MySQL' 'mysql -uroot'

# Set default window
tmux select-window -t $SESSION:1

# Attach to session
tmux -2 attach-session -t $SESSION

You can view the (up to date) origin of this script at GitHub.

So what exactly does this script do?

  1. It creates a new tmux session.
  2. It creates a new window called ‘Logs’ which is split into a grid of 2×2 with the bottom 2 panes being smaller in size (height). In every pane a command is executed. For example in pane 0 the command tail -f /vagrant/maximus.log gets executed.
  3. A second window called ‘MySQL’ is created which runs the mysql -uroot command.
  4. Then we switch back to the first window (actually second, as tmux pane numbers start with 0) which is the window that shows us the contents of these log files.
  5. Finally we attach to the tmux session.

The added benefit of this small script is that from now on all I have to do is run it and my tmux session will be configured for this specific project (Maximus in this case).

I’ve also found some other useful tmux resources as well which are listed below: