Cycle Tmux Sessions In Order

Tmux includes a switch-client command which allows you to switch to the previous or next session which is handy for quickly jumping between open sessions. However, it doesn’t behave in the way you might expect as it orders sessions based on most recently visited, rather than when the session was created. For me, this just isn’t how I think about my Tmux sessions, so I had to find another way.

To get started, we need to build a shell script that will switch to the next/previous session. This is not very straightforward, since Tmux doesn’t have the concept of session index, the index is merely there as a result of printing sessions in chronological order. In the script below, we are able to print the order of our Tmux sessions, sort by created date, and then use the resulting list for session index lookups and to find the next session in the list.

~/.config/tmux/scripts/switch-client.sh
#!/usr/bin/env bash

# List all sessions, sorted by creation time
sessions=$(tmux list-sessions -F "#{session_created} #{session_name}" | sort -n | awk '{print $2}')

# Get the current session name
current_session=$(tmux display-message -p '#{session_name}')

# Get the total number of sessions
total_sessions=$(echo "$sessions" | wc -l)

# Get the current session index
current_index=$(echo "$sessions" | grep -n "^$current_session$" | cut -d: -f1)

# Get the next session index based on the direction, loop around if necessary
if [[ "$1" == "1" ]]; then
	next_index=$((current_index % total_sessions + 1))
else
	next_index=$(((current_index - 2 + total_sessions) % total_sessions + 1))
fi

# Find the session by index and switch to it
tmux switch-client -t "$(echo "$sessions" | sed -n "${next_index}p")"

With this script in place, we can simply add some keybindings to our Tmux config (I chose prefix+u for previous and prefix+n for next).

~/.config/tmux/tmux.conf
bind u run-shell "~/.config/tmux/scripts/switch-client.sh -1"
bind n run-shell "~/.config/tmux/scripts/switch-client.sh 1"