For many years, I have been guilty of always recreating an ssh-agent instead of reusing the previous one. I know, it's an atrocity and a waste of CPU cycles and registers. It had to stop.

Every time I would try to use a ssh-key via ssh-add, I'd see the dreaded

Could not open a connection to your authentication agent.

message and I would just mindlessly run eval $(ssh-agent). With time, this would leave an army of ssh-agent processes behind my back..

So I am finally writing this tiny article as a reminder to not ever do it again. There's a few Stack Overflow answers on the matter, but for me the only way to burn it into my memory is to force myself to write about it.

It's all about the environment

Truth to be told, it is so easy to reuse an ssh-agent that I feel guilty for my lazyness. The only 2 environment variables needed are the SSH_AGENT_PID and SSH_AUTH_SOCK. Specifically for ssh-add, the SSH_AGENT_PID is not even needed (see man ssh-add), but it doesn't hurt to be set.

According to man ssh-agent :

SSH_AGENT_PID When ssh-agent starts, it stores the name of the agent's process ID (PID) in this variable.

SSH_AUTH_SOCK When ssh-agent starts, it creates a Unix-domain socket and stores its pathname in this variable. It is accessible only to the current user, but is easily abused by root or another instance of the same user.

Armed with this knowledge, we're just two lines away from being able to reuse an existing ssh-agent:

$ export SSH_AGENT_PID=$thepid
$ export SSH_AUTH_SOCK=$thesocketpath

Of course, we need to know what to put on the right hand side of the assignment. The pid is pretty easy to find, you can do something ps aux | grep ssh-agent and copy from it.

A one-liner might look like this:

$ ps aux | grep ssh-agent | head -n1 | awk '{print $2}'

For the socket path, in my experience it tends to live in /tmp/ssh-$SOMEID/agent.$SOMEOTHERID

A one-liner to find it might look like this:

$ find /tmp/ssh-* -type s -name "*agent*"

Further reading

If you want to be a lot more sophisticated about it, have a read here:

For the time being, I find it easy enough to make bash aliases to help me set these variables when needed, but of course you can script the hell out of it if you really want to.

Of course, somebody already scripted it for you, so you might want to use their code instead: