Skip to main content
  1. Posts/

Fuzzy-switching Tmux Sessions with Ease

··365 words·2 mins·
Table of Contents

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 (check the title image).

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:

#!/bin/bash
tmuxsessions=$(tmux list-sessions -F "#{session_name}")

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

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.

References
#

Related

Tmux Questions and Trouble Shootings
··1163 words·6 mins
Building and Install Tmux from Source on Linux
··441 words·3 mins
Vim-like Settings for Tmux
··425 words·2 mins