How to swap windows in tmux?

Quick Answer

Swap tmux windows using swap-window command. To move window 2 to position 1: Ctrl+b :swap-window -s 2 -t 1. To swap current window with window 3: Ctrl+b :swap-window -t 3. You can also create custom key bindings for frequent window swaps.

Ctrl+b :swap-window -t [target]

Detailed Explanation

As your tmux session grows, you might want to rearrange windows to group related tasks together or place frequently used windows in more accessible positions. tmux provides several methods to swap and reorder windows.

Basic window swapping commands:

# Swap current window with window number 3
Ctrl+b :swap-window -t 3

# Swap window 2 with window 1
Ctrl+b :swap-window -s 2 -t 1

# Move current window to position 0 (first position)
Ctrl+b :swap-window -t 0

# Move window 3 to the end (highest number)
Ctrl+b :swap-window -s 3 -t +1

Understanding the syntax:

The swap-window command uses the following parameters:

  • -s: Source window (the window to move)
  • -t: Target destination (where to move it to)

If you omit the -s parameter, tmux uses the current window as the source.

Moving windows to specific positions:

# Move current window to the far left (index 0)
Ctrl+b :move-window -t 0

# Move window to a specific position
Ctrl+b :move-window -t 2

# Move window 3 to the first position
Ctrl+b :move-window -s 3 -t 0

Note: move-window is equivalent to swap-window in tmux.

Creating custom key bindings for window swapping:

Add these lines to your ~/.tmux.conf to create shortcuts for moving windows:

# Shift+Left/Right to move windows left/right
bind-key -n S-Left swap-window -t -1
bind-key -n S-Right swap-window -t +1

# Ctrl+Shift+Left/Right for alternative bindings
bind-key -n C-S-Left swap-window -t -1
bind-key -n C-S-Right swap-window -t +1

With these bindings, you can press Shift+Left to move the current window one position to the left, or Shift+Right to move it one position to the right.

Handling errors when swapping windows:

If you try to swap with a window index that doesn't exist, tmux will show an error. To avoid this, you can first check what windows exist using:

Ctrl+b w

This displays a list of all windows in the current session, making it easier to select the correct target index.

Pro Tip

To keep your window indexes sequential after closing windows, add this to your ~/.tmux.conf:

# Automatically renumber windows when one is closed
set -g renumber-windows on

This ensures that window numbers are always contiguous, making window management more predictable.