Start tmux automatically

I wanted to start tmux—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).

The 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 script 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

main_session_name="main"
>/dev/null 2>&1 tmux has-session -t $main_session_name

if [ $? != "0" ]
then
    # does not exist, so create and attach to it
    tmux new -s $main_session_name
else
    # exists, check number of clients
    nclients="$(tmux list-clients -t $main_session_name | wc -l)"
    if [ $nclients = "0" ]
    then
        # no clients, be the first one to attach to it
        tmux attach -t $main_session_name
    else
        # has clients, so create a new unnamed session
        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, or use the “Run command instead of my shell” option of your terminal emulator to run the program.

 
3
Kudos
 
3
Kudos

Now read this

Accidental removal of side-effect imports

Go has the ability to import a package purely for the package’s side-effects (i.e. you don’t actually use a symbol from the package in your code, but just want side-effects introduced by the package). As an example, look at package... Continue →