I use tmux an awful lot at work since it allows for a workflow where each session name references a separate piece of work that may need to be returned to (it’s impossible to know upfront) and if it does it’s far easier to pull up the previous session than start off from scratch.

However, the problem with this approach is it’s really easy to rapidly accumulate sessions and to have no idea which ones I need to keep hanging around which is how I regularly end up with fifty sessions; in fact it’s really not unusual for me to end up with over a hundred sessions.

This means every few weeks I need to purge my sessions. Until I’ve figured out a way to automatically look up the work id and see if it’s closed (there is an API, but I’ve not figured if that kind of query is possible yet) I either have to close one at a time or hope there is just one session I want to keep so I can use tmux kill-session -a -t theoneIwanttokeep. Which is great if there is just one I want to keep, but invariably I know for a fact there are four or five I want.

So I finally wrote a simple script to do just that:

for i in $(tmux list-sessions -F '#S'); do
  if [[ ! $@ =~ $i ]]; then
    tmux kill-session -t $i

Then I can call this as ./tkse sessiona sessionb sessionc sessiond, etc and it’ll kill everything except those sessions.

This won’t work if a session name has a space in it, but what kind of heathen does that?