Posted on :: Tags: , , , ,

I use a new Tmux session for each day. Over time, I noticed that sessions proliferate, and I often need windows from earlier sessions in a central location.

This script merges all windows from all Tmux sessions into a single session. You must specify the target session as a parameter. If you save the script as merge-tmux-sessions.zsh, you can run it like:

merge-tmux-sessions.zsh my-current-session

It will then move all windows into the session you specify.

#!/bin/zsh

# set -vuex
#
#  Specify the target session

target_session=$1

# Get the list of all sessions

sessions=$(tmux list-sessions -F '#S')

# Iterate through each session

for session in ${(@f)sessions}; do
    if [ "$session" != "$target_session" ]; then
        # Get the list of windows in the current session
        windows=$(tmux list-windows -t $session -F '#I')

        # Move each window to the target session
        for window in ${(@f)windows}; do
            tmux move-window -s ${session}:${window} -t ${target_session}
        done
    fi

done