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.

#!/usr/bin/env bash

set -u

tmux has-session -t main 2>&1 > /dev/null

if [ $? -ne "0" ]
    # does not exist, so create it
    tmux new -s main
    # exists, check number of clients
    NCLIENTS=$(tmux list-clients -t main | wc -l)
    if [ $NCLIENTS -eq "0" ]
        # no clients, be the first one to attach to it
        tmux attach -t main
        # has clients, so create a new unnamed session
        tmux new

Save this script to a file like $HOME/bin/tmux_new and make it executable (chmod +x ...). Then update the “Run command instead of my shell” option of your terminal emulator to use this script.


Now read this

Hibernate in Fedora

I spent time yesterday making HybridSleep and Hibernate work in Fedora 32 on a ThinkPad X1 Carbon with an encrypted disk. I don’t ever plan to manually use hybrid sleep or hibernate; I’d instead just lock my screen or close the laptop... Continue →