Skip to content

Instantly share code, notes, and snippets.

@eginez
Last active October 19, 2025 04:16
Show Gist options
  • Select an option

  • Save eginez/f5b70a895328f6948b940fb8568d1e3f to your computer and use it in GitHub Desktop.

Select an option

Save eginez/f5b70a895328f6948b940fb8568d1e3f to your computer and use it in GitHub Desktop.
Fix SSH agent forwarding in tmux after detach/reattach

Fixing SSH Agent Forwarding in tmux

The Problem

When you SSH into a remote host with agent forwarding (ssh -A) and start a tmux session, everything works fine. But when you disconnect and reconnect later, SSH agent forwarding stops working inside your existing tmux session.

Why This Happens

Each time you SSH in, a new authentication socket is created at a path like /tmp/ssh-XXXXXX/agent.12345. When you start tmux, it captures this socket path in SSH_AUTH_SOCK.

When you disconnect and reconnect:

  • Your new SSH session creates a new socket (e.g., /tmp/ssh-YYYYYY/agent.67890)
  • tmux updates its environment with the new socket
  • But your existing shell sessions inside tmux still point to the old, now-invalid socket

Symptoms

# Inside tmux after reconnecting
$ ssh-add -l
Could not open a connection to your authentication agent.

$ echo $SSH_AUTH_SOCK
/tmp/ssh-rT2D758KaF/agent.458032  # Old socket

$ tmux show-environment | grep SSH_AUTH_SOCK
SSH_AUTH_SOCK=/tmp/ssh-4ygs8ipXS2/agent.468415  # New socket

Solutions

Quick Fix (Manual)

Add

# Fix SSH agent forwarding in tmux
if [ -n "$TMUX" ]; then
  eval $(tmux show-environment -s SSH_AUTH_SOCK)
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment