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

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 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.

--

--

--

Data science specialist and digital methods researcher. <nelsonaloysio.github.io> 🇧🇷

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

AWS CDK and Typescript: Deploy an API Server to AWS Lambda

Connecting Your Google Colab and Google Drive

Libra ❤ Docker

Multi-processing Image Evolution In Python

Experimentor Weekly Journal — 02

Yes, I am a fullstack developer.

Understanding isolates in Flutter

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nelson Aloysio

Nelson Aloysio

Data science specialist and digital methods researcher. <nelsonaloysio.github.io> 🇧🇷

More from Medium

Containerization with Podman and Buildah: Linux containers and OCI images explained

Notifications for failed cron jobs

How to setup SSH certificates for SSH authentication

*Nix File System Hierarchy Explained