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.


While tmux updates SSH variables by default, there is no need to

  • change/add socket path
  • change the SSH_AUTH_SOCKET variable

I like the solution by Chris Down which I changed to add function

fixssh() {
    eval $(tmux show-env    \
        |sed -n 's/^\(SSH_[^=]*\)=\(.*\)/export \1="\2"/p')
}

into ~/.bashrc. Call fixssh after attaching session or before ssh/scp/rsync.

Newer versions of tmux support -s option for show-env, so only

eval $(tmux show-env -s |grep '^SSH_')

is possible.


Here's what I use for updating SSH_AUTH_SOCK inside a tmux window (based on Hans Ginzel's script):

alias fixssh='eval $(tmux showenv -s SSH_AUTH_SOCK)'

Or for tmux that does not have showenv -s:

alias fixssh='export $(tmux showenv SSH_AUTH_SOCK)'

Here is my solution which includes both approaches, and does not require extra typing when I reconnect to tmux session

alias ssh='[ -n "$TMUX" ] && eval $(tmux showenv -s SSH_AUTH_SOCK); /usr/bin/ssh'

There are lots of good answers here. But there are cases where tmux show-environment doesn't see SSH_AUTH_SOCK. In that case you can use find to locate it explicitly.

export SSH_AUTH_SOCK=$(find /tmp -path '*/ssh-*' -name 'agent*' -uid $(id -u) 2>/dev/null | tail -n1)

That's long and complicated, so I'll break it down...

01  export SSH_AUTH_SOCK=$(
02    find /tmp \
03      -path '*/ssh-*'
04      -name 'agent*'
05      -uid $(id -u)
06      2>/dev/null
07    | tail -n1
08  )
  1. export the SSH_AUTH_SOCK environment variable set to the output of the $() command substitution
  2. find files starting in /tmp
  3. limit results to only those with /ssh- in the path
  4. limit results to only those whose name begins with agent
  5. limit results to only those with a user id matching the current user
  6. silence all (permissions, etc.) errors
  7. take only the last result if there are multiple

You may be able to leave off 6 & 7 if you know that there will only be 1 result and you don't care about stderr garbage.