Tmux scripts can be used for automating the setup of tmux environments you frequently use.

Sometimes when using tmux you'll find yourself repeating certain tmux commands for setting up a certain environment you use multiple times. For example, when I use tmux for editing, compiling and viewing a latex document, I'll set up a tmux window consisting of three panes:

  • a pane for compiling the tex file
  • a pane for viewing the generated pdf file in a pdf viewer (e.g. evince)
  • a pane for editing the tex file

I can automate this setup with the following script

#!/bin/bash

# kill a possible existing tmux session before setting a new one
tmux kill-session -t latex

# create a new tmux session with the name set to "latex"
tmux new -s latex -d

# create two additional tmux panes by splitting the latex tmux window
tmux split-window -v -t latex
tmux split-window -v -t latex

# run the pdf viewer "evince" in the second pane
tmux send-keys -t latex:0.1 'evince main.pdf' C-m

# run vim in the third pane for editing the LaTeX file
tmux send-keys -t latex:0.2 'vim main.tex' C-m

# set the layout to tiles to create a nice environment
tmux select-layout -t latex tiled

# attach to the newly created tmux session
tmux a -t latex

The resulting session looks like this:

tmux latex

The next time I want to edit a LaTeX document, I just need to run this script and I'm instantly ready to begin using the created tmux session and start editing.

This is a very simple example, but you can do a lot more with tmux scripts to automate certain repetetive tasks. Another example for which I've used a tmux script is in my computer science group project (Problem Solving And Design). We have to run a server on a Raspberry Pi to host a user interface to control the robot the Raspberry Pi is attached to. The tmux session we created sets up and starts the server and the camera stream. We can then watch the logs of those two programs in the tmux session. For debugging we frequently need to restart the server. With the script its really easy and quick to do that. Another advantage is that if we switch networks on our laptops from the local network on the Raspberry Pi to the University network for accessing the internet we don't lose the tmux session. So when we reconnect we only need to reattach to the tmux session instead of needing to restart the server and camera stream.