Start tmux automatically

I wanted to start tmux(1)—the terminal multiplexer—automatically when I opened a new terminal window.

I had some specific requirements however. For instance, I wanted to have a "main" tmux session that new windows should try to attach to. And if I was already attached to the main tmux session, then I wanted any subsequent new terminal windows to create new unnamed sessions (this way each window has its own independent session).

Requirements

  1. If the "main" session doesn't exist, create a new session named "main".
  2. If the "main" session exists and there are zero clients attached to it, attach to it ourselves.
  3. If the "main" session exists and there is already a client attached to it, create a new unnamed session.

I wrote a program to do this, since it seems like tmux's built-in subcommands and flags can't account for these requirements on their own. The command tmux new -A -s main comes close but doesn't meet the third requirement.

#! /bin/bash
# mux: tmux session helper

set -u

# the name of the main session.
session="main"

>/dev/null 2>&1 tmux has-session -t "$session"
if [ $? != "0" ]; then
    # create named session.
    tmux new -s "$session"
else
    # attach to the existing one if it has zero clients,
    # otherwise create an unnamed session.
    nclients="$(tmux list-clients -t "$session" | wc -l | xargs)"
    if [ $nclients = "0" ]; then
        tmux attach -t "$session"
    else
        tmux new
    fi
fi

Save this script to a file like $HOME/bin/mux and make it executable (chmod +x ...). Then either run the program in your shell's rc file (but only if $TMUX is unset to avoid nesting of tmux sessions), or use the "Run command instead of my shell" option of your terminal emulator to run the program.