November 18, 2024

Automatically start tmux in bash

I have become accustomed to having tmux running, which allows me to keep a single terminal open on my screen and create as many sub-terminals as I need in my work.

However, I don’t want to have to remember to start tmux every time I start a terminal, and often I forget until the first time I try to split the pane or create a new tmux window.

I also am in the habit of exiting shells manually (rather that close the whole terminal window), but if I start tmux manually, I have to exit both tmux and the shell itself, which gets tiresome.

To address both of these things, I put the following at the top of my .bashrc:

if [ ! "$TMUX" ]; then
  exec bash -c 'tmux new-session'
fi

This bash code starts a new tmux session for every terminal I start (unless the TMUX variable is set, which indicates we’re already in a tmux session. We use exec because we want to replace the launching process with the new process (tmux). By replacing the parent /bin/bash process with the child tmux process, we can exit the whole shell with one exit call.

This does potentially create a bunch of tmux sessions if we open multiple terminals, but that’s okay, it’s actually sort of nice to be able to recover a closed terminal session. Here’s how to do that:

First, we can list the existing tmux sessions. I’ve named some of these strangely, but the names (e.g. sess1) don’t matter, they are just names:

$ tmux ls
5: 1 windows (created Mon Nov 18 23:14:41 2024)
sess1: 2 windows (created Mon Nov 18 23:06:07 2024) (attached)
sess2: 1 windows (created Mon Nov 18 23:06:11 2024)
sess3: 1 windows (created Mon Nov 18 23:06:19 2024)

If we’re in a tmux session (which we probably are if we are using this pattern of creating a session on every terminal open), we’ll have to use ‘switch-client’. The following will transfer us from session sess1 to session sess2:

$ tmux switch-client -t sess2

© Brandon Atkinson 2024

Powered by Hugo & Kiss.