How to check if ssh-agent is already running and automatically load it (Linux/WSL)

Nelson Aloysio
2 min readJan 15, 2022
Figure: gnome-terminal displaying output from command `ps x | grep ssh`.

SSH is a great open-source tool (thanks, @tjssh!) used daily & worldwide.

In order to avoid running multiple instances of the ssh-agent helper unknowingly, it’s best to first check if there is an already active (as in, loaded/running) process. Looking for a recommended way to do so on Stack Overflow, though, I was left unsatisfied with the methods I found, which resorted to wrapper scripts or killing and restarting previously loaded instances of it. After writing my own solution, I figured I’d best share it with others and that it might as well make a good-enough first post.

So — easiest way I found was to append this code block to my ~/.bashrc:

#!/usr/bin/env bash

# SSH_AUTH_SOCK="$HOME/.ssh-agent.socket"

[ -z "$SSH_AGENT_PID" ] &&
export SSH_AGENT_PID=$(ps ux | grep -w ssh-agent | grep -vwE 'defunct|grep' | grep -wm1 "$SSH_AUTH_SOCK" | awk '{print $2}')

[ -n "$SSH_AGENT_PID" ] && [ -z "$SSH_AUTH_SOCK" ] &&
export SSH_AUTH_SOCK=$( (ps "$SSH_AGENT_PID" | grep -w -- '-a' | sed "s/.* -a //;s/ .*//" | grep -- /) || (find /tmp/ssh-* -name \*$(($SSH_AGENT_PID-1)) -o -name \*$(($SSH_AGENT_PID-2)) -type s 2> /dev/null) )

( [ -z "$SSH_AGENT_PID" ] || [ -z "$SSH_AUTH_SOCK" ] ) &&
eval $(ssh-agent $([ -n "$SSH_AUTH_SOCK" ] && rm -f "$SSH_AUTH_SOCK" && echo -n "-a $SSH_AUTH_SOCK") -s) 1> /dev/null

That way, if an agent is already running, it’ll recover its process ID number (SSH_AGENT_PID) and the bind address of the socket to communicate with other processes (SSH_AUTH_SOCK) — by default found in $TMPDIR/ssh-*/agent.<ppid>, if not custom set. Otherwise, it will start up the agent.

Note that you may choose to set a custom path for the file socket (line #3), which is advisable in case you need to run multiple agents per user. Only paths that do not contain spaces will work when invoking a new shell.

Alternatively, you may also add the code block above to a different file and source it from ~/.bashrc (or to ~/.zshrc.local, if you are using ZSH).

Updated on February 28, 2023 to support running multiple agents.
Updated on August 24, 2023 to support system-defined file sockets.
Updated on February 7, 2024 to use more strict (and readable) conditions.

--

--