During my work, I use multiple Tmux sessions to manage different projects. When I create a new session, I usually give it unique name so that I know that the project is about via the session name.

switching between sessions – the basic way

Tmux has a builtin subcommand called choose-session. Initially, I add a key binding for this command in my .tmux.conf:

bind-key S choose-session

It works by showing a list of sessions, and you can switch between these sessions by using Ctrl-N and Ctrl-P.

One disadvantage with this method is that we can only switch between different session one at a time. When I have multiple sessions, switching between them is a pain.

fuzzy-switching sessions with fzf

A more advanced way is to use fzf to filter sessions by their name and then switch to the selected session.

First, we create a shell script ~/.tmux/tmux-switch-session.sh1:

tmuxsessions=$(tmux list-sessions -F "#{session_name}")

tmux_switch_to_session() {
    if [[ $tmuxsessions = *"$session"* ]]; then
        tmux switch-client -t "$session"

choice=$(sort -rfu <<< "$tmuxsessions" \
    | fzf-tmux \
    | tr -d '\n')
tmux_switch_to_session "$choice"

We need to give this script execution rights (solution found here):

chmod +x ~/.tmux/tmux-switch-session.sh

Otherwise, when trying to run this script using key bindings, we get the following error:

/home/jdhao/.tmux/tmux_switch_to_session returned 126

Then add the following config to tmux conf:

bind-key S run-shell -b "~/.tmux/tmux-switch-session.sh"

Note that -b option for run-shell subcommand is important, without which, tmux will stuck and freeze forever, see also this issue.

switching tmux sessions with menu

This post shows how to switch sessions using a menu, which is also cool.

First, we create a script ~/.tmux/session-menu (do not forget to give it execution rights):

#!/usr/bin/env bash

# See https://qmacro.org/autodidactics/2021/08/12/session-switching-with-the-tmux-menu/

tmux list-sessions -F '#S' \
  | awk 'BEGIN {ORS=" "} {print $1, NR, "\"switch-client -t", $1 "\""}' \
  | xargs tmux display-menu -T "Switch-session"

Then we create a key binding for it in tmux conf:

bind-key ` run-shell -b "~/.tmux/session-menu"

It will show a small menu for you to switch between different sessions. Pressing a number will switch to that session.


  1. Source here: https://www.reddit.com/r/tmux/comments/9qluuf/comment/e8bml7m/ ↩︎