exupero's blog

Tmux session launcher

In the previous post I described using Tmux as a development environment. To create a new session based in a directory, or to attach to an existing session, I use a Bash script, called, for a reason I've forgotten, zmux:

if [ -n "$1" ] && [ -n "$(tmux list-sessions -F '#S' | grep "^$1\$")" ]; then
  tmux -2 attach -t $1
elif cd $1; then
  if [ -e ".tmuxrc"]; then
    tmux -2 new \; source-file .tmuxrc \; attach
    tmux -2 new \; attach
  echo "'$1' directory or session does not exist"
  exit 1

The script takes a single argument that it uses to find an existing Tmux session or a directory. If it finds a session, it attaches to it. If it finds a folder, it creates a new session in it and attaches to it. (The argument -2 tells Tmux to assume support for 256 colors.)

When launching a session for a new directory, the script also looks for a .tmuxrc file. If it finds one, it sources it to set up the session with my preferred windows, panes, and long-running processes. That's especially useful for projects I haven't touched in a long time, for which it can be difficult to remember the commands that run the build or server daemons. Here's an example .tmuxrc:

rename-session api

rename-window main
send "vim" C-m
split-window -h
resize-pane -x 80

new-window -t 8 -n tools
send "vim +'tab all' .vimlocal .snippets" C-m

new-window -t 9 -n daemons
send "./server.sh" C-m

Often, however, my .tmuxrc setup is simpler and I have other scripts to configure windows and panes as needed, which I'll describe more in a later post.