How to auto-update SSH agent environment variables when attaching to existing tmux sessions?

There’s an excellent gist by Martijn Vermaat, which addresses your problem in great depth, although it is intended for screen users, so I’m adjusting it for tmux here.

To summarize:

  1. create ~/.ssh/rc if it doesn’t exist yet, and add the following content:

    #!/bin/bash
    
    # Fix SSH auth socket location so agent forwarding works with tmux.
    if test "$SSH_AUTH_SOCK" ; then
      ln -sf $SSH_AUTH_SOCK ~/.ssh/ssh_auth_sock
    fi
    
  2. Make it work in tmux, add this to your ~/.tmux.conf:

    # fix ssh agent when tmux is detached
    setenv -g SSH_AUTH_SOCK $HOME/.ssh/ssh_auth_sock
    

Extra work is required if you want to enable X11 forwarding, see the gist.

Leave a Comment