Bits and bytes of code
Bytes is my collection of short-form posts, tips, and things I learn as I build software.
Bytes is my collection of short-form posts, tips, and things I learn as I build software.
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.
#!/usr/bin/env bash
# List all sessions, sorted by creation time
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).
bind u run-shell "~/.config/tmux/scripts/switch-client.sh -1"
bind n run-shell "~/.config/tmux/scripts/switch-client.sh 1"