Skip to content

Instantly share code, notes, and snippets.

@seraphyn
Forked from darrenpmeyer/README.md
Created May 22, 2023 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seraphyn/20679ebf7a3bb3e9a528452d2e2b7810 to your computer and use it in GitHub Desktop.
Save seraphyn/20679ebf7a3bb3e9a528452d2e2b7810 to your computer and use it in GitHub Desktop.
Automatically start a single instance of ssh-agent for all terminal sessions to share (bash)

Installation

  1. mkdir -p ~/.config && touch ~/.config/ssh-agent.pid
  2. Paste the contents of ssh-agent-manage.sh into your .bashrc or .bash_profile or similar
  3. killall -9 ssh-agent
  4. Start a new terminal session (note: old sessions will not see ssh-agent, only new ones)

Details

This snippet, when included in .bashrc, will ensure that your session has a working ssh-agent with all your ssh keys loaded into it. It does this without creating separate ssh-agent processes by:

  • Using ~/.config/ssh-agent.socket as the socket, rather than a random-named temporary socket
  • Tracking the PID of ssh-agent in ~/.config/ssh-agent.pid
  • setting up the appropriate environment variables to point to any already-running ssh-agent started this way (NB: if you start an agent process by hand, this won't know about it)
  • starting up an ssh-agent if it can't find a properly-configured version already running
# SSH agent
ssh_pid_file="$HOME/.config/ssh-agent.pid"
SSH_AUTH_SOCK="$HOME/.config/ssh-agent.sock"
if [ -z "$SSH_AGENT_PID" ]
then
# no PID exported, try to get it from pidfile
SSH_AGENT_PID=$(cat "$ssh_pid_file")
fi
if ! kill -0 $SSH_AGENT_PID &> /dev/null
then
# the agent is not running, start it
rm "$SSH_AUTH_SOCK" &> /dev/null
>&2 echo "Starting SSH agent, since it's not running; this can take a moment"
eval "$(ssh-agent -s -a "$SSH_AUTH_SOCK")"
echo "$SSH_AGENT_PID" > "$ssh_pid_file"
ssh-add -A 2>/dev/null
>&2 echo "Started ssh-agent with '$SSH_AUTH_SOCK'"
# else
# >&2 echo "ssh-agent on '$SSH_AUTH_SOCK' ($SSH_AGENT_PID)"
fi
export SSH_AGENT_PID
export SSH_AUTH_SOCK
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment