Skip to content

Instantly share code, notes, and snippets.

@hilbix
Last active April 24, 2017 11:39
Show Gist options
  • Save hilbix/7d3bacb1b91cdf6df5c6 to your computer and use it in GitHub Desktop.
Save hilbix/7d3bacb1b91cdf6df5c6 to your computer and use it in GitHub Desktop.
Allow SSH_AUTH_SOCK to roam (use a working agent connection)
# Following remembers possible agent connections,
# switches to some still open connection if the current one fails,
# and pins SSH_AUTH_SOCK to a fixed location
# such that you never need to worry about breaking connections.
#
# This perhaps is bash only. Source this in your .bashrc or .bash_aliases
# Currently needs "timeout" installed as well.
# See https://gist.github.com/hilbix/7d3bacb1b91cdf6df5c6
permanent_auth_sock_hack()
{
local auth a
auth="$HOME/.ssh/.agent.sock"
# remember authentication sockets
[ -n "$SSH_AUTH_SOCK" ] &&
[ ".$auth" != ".$SSH_AUTH_SOCK" ] &&
[ -S "$SSH_AUTH_SOCK" ] &&
ln --backup=t -sn "$SSH_AUTH_SOCK" "$auth."
# pin it
export SSH_AUTH_SOCK="$auth"
# choose a working one
timeout 0.3 ssh-add -l >/dev/null ||
for a in "$auth."*
do
ln -fn "$a" "$auth"
timeout 2 ssh-add -l >/dev/null 2>/dev/null || { rm -f "$a"; continue; }
echo "Working connection to authentication agent found." >&2
break
done
}
permanent_auth_sock_hack
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment