Fixing stale SSH sockets in tmux

Update (as of 2015-10-12)

This is actually available by default in modern versions of tmux: just add SSH_AUTH_SOCK to an update-environment call in your tmux configuration.

The rest of this article is only preserved as a record, I suggest you use update-environment (see man tmux) instead.


I use tmux on my devbox with ssh-agent forwarding, so that I can access our git server transparently. Unfortunately, when reattaching to a tmux session, you'll get the old SSH_AUTH_SOCK, and there's no immediate way to update this. I wrote this function, which fixes this (run it after attaching):

update_auth_sock() {
    local socket_path="$(tmux show-environment | sed -n 's/^SSH_AUTH_SOCK=//p')"

    if ! [[ "$socket_path" ]]; then
        echo 'no socket path' >&2
        return 1
    else
        export SSH_AUTH_SOCK="$socket_path"
    fi
}

Trent Lloyd suggests an alternative method; symlinking the path pointed to by SSH_AUTH_SOCK on login, and then changing it to point to the symlink. As long as you are either only using a single key to log in and forward to each server, or you have some way of determining the identity of the key on the remote, this is a more easily automatable solution.