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).
- If the “main” session doesn’t exist, create a new session named “main”.
- If the “main” session exists and there are zero clients attached to it, attach to it ourselves.
- 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" ] then # does not exist, so create it tmux new -s main else # exists, check number of clients NCLIENTS=$(tmux list-clients -t main | wc -l) if [ $NCLIENTS -eq "0" ] then # no clients, be the first one to attach to it tmux attach -t main else # has clients, so create a new unnamed session tmux new fi fi
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.