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

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 majoritively 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 Medium post.
So — easiest way I found was to append this “one-liner” to my~/.bashrc file:
[ $(ps x |
grep -vE "defunct|grep" |
grep -vw '\-a' |
grep -cw ssh-agent ) -gt 0 ] &&
export SSH_AGENT_PID=$(
ps x | grep ssh-agent | head -n1 | awk '{print $1}' ) &&
export SSH_AUTH_SOCK=$(
ls -1 /tmp/ssh-*/agent.$(
ls -1 /tmp/ssh-*/agent.* |
cut -f2 -d. |
sort -n |
head -n1 ) ) ||
eval $(ssh-agent -s) 1> /dev/null
That way, if an agent is already running, it’ll recover its process ID number (SSH_AGENT_PID) and the path of the file socket that the agent uses to communicate with other processes (SSH_AUTH_SOCK) — which is generally, but not always equal to the process ID minus one. If multiple agents are running, it will consider the first launched; and if there aren’t any, then it’ll just start the agent — mainly useful for distributions or alternatives to run Linux that don’t come preconfigured to autostart it on boot/login time.
(I actually have a different file named .bashrc.local with my own settings, separate from the system’s, which I source when running bash and/or zsh — but I guessed this example would be most straightforward that way).
Tested and working both on Arch Linux and WSL.