exupero's blog
RSSApps

Tmux session finder

On one project I worked on, I had a Tmux session for the frontend code and build process, another for the backend API code and server, and a third, parent project that tied them together. Mixed in among these were some unrelated sessions. Switching frequently between the project sessions became a minor hassle with Tmux's built-in session picker, which is a list of names you have to cursor through. Usually I didn't need to browse the list, I knew the name of the session I wanted to switch to, and having to find it became a small annoyance.

To switch to a session by name, I wrote the script fuzzy-match-tmux-session:

pattern=$(echo $1 | sed -e 's/./&.*/g')
if tmux list-sessions -F '#S' | grep -q "^$1\$"; then
  session=$1
else
  session=$(tmux list-sessions -F '#S' | grep $pattern | head -1)
fi

if [[ -n "$2" ]]; then
  tmux switch-client -t $session \; select-window -t $2
else
  tmux switch-client -t $session
fi

The script takes one or two arguments. The first is used to look for a session name, preferring a complete match to a partial match. The second, optional argument allows selecting a specific window in the target session.

I've bound the script to a Tmux keystroke:

bind g command-prompt -p "Session:" \
  "run-shell -b \"fuzzy-match-tmux-session %%%\""

I still occasionally use this binding, but I don't rely on it like I did when I worked on the project that inspired it. These days I do have many Tmux sessions running at once, but they're workspaces for Git worktrees, and their session names are based on the branch they have checked out, which means they change frequently and are much harder to call to mind when I want to switch sessions. I can, however, recognize the name of the branch I want when I see it, a case for which Tmux's built-in session picker works well.