Skip to content

Instantly share code, notes, and snippets.

@archon810
Last active November 18, 2025 23:08
Show Gist options
  • Select an option

  • Save archon810/dadd6bc86732d13cb5a957b146dd2362 to your computer and use it in GitHub Desktop.

Select an option

Save archon810/dadd6bc86732d13cb5a957b146dd2362 to your computer and use it in GitHub Desktop.
Robust way to make ssh key forwarding work with multiple possible sockets/sessions, especially handy in screen
# Make ssh key forwarding work with multiple possible sockets/sessions, especially handy in screen
# Updated for the new openssh 10.1/10.2 change that moved the sockets location from /tmp/ssh-XXXXXX/ to $HOME/.ssh/agent/
update_ssh_auth_sock() {
local sock
# Find newest alive socket
for f in $(ls -t $HOME/.ssh/agent/* 2>/dev/null); do
if [ -S "$f" ]; then
if SSH_AUTH_SOCK="$f" ssh-add -l >/dev/null 2>&1; then
export SSH_AUTH_SOCK="$f"
#echo "Found a new live SSH_AUTH_SOCK $f"
return 0
fi
fi
done
unset SSH_AUTH_SOCK
return 1
}
# Auto-update only if current socket is dead (efficient)
update_ssh_auth_sock_quiet() {
if [ -n "$SSH_AUTH_SOCK" ]; then
# Quick test - if dead, find new one
SSH_AUTH_SOCK="$SSH_AUTH_SOCK" ssh-add -l >/dev/null 2>&1 || update_ssh_auth_sock
else
update_ssh_auth_sock
fi
}
# Wrapper for git
git() {
update_ssh_auth_sock_quiet
command git "$@"
}
# Wrapper for ssh
ssh() {
update_ssh_auth_sock_quiet
command ssh "$@"
}
# Or instead of the above wrappers, enable this if you want the lite socket liveliness check to run
# before every shell command, though it could be overkill for many and ssh/git wrappers are enough
#PROMPT_COMMAND="update_ssh_auth_sock_quiet; ${PROMPT_COMMAND:-}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment