Reuse existing ssh agent

Reuse existing ssh agent

I have a simple script that I run to load my ssh keys into ssh agent. It looks like this:-

eval "$(ssh-agent)"
ssh-add

The problem is, I have to run this in every new terminal I started. And that means typing the key passphrase every single time. Since all it does is just running the agent and then setting environment variable pointing to the agent’s socket, made me thinking what if I can just re-use the existing agent instead of running new one.

These days, once you know what you want to have, it just a matter of prompting AI chatbot to write the code for you. I use Claude most of the time for coding, so this is what I got after a few prompts:-

#!/bin/bash

#eval "$(ssh-agent)"
#ssh-add

# Function to find existing SSH agent
find_ssh_agent() {
    echo "Look for existing ssh-agent processes"
    AGENT_PID=$(pgrep -u $USER ssh-agent)
    if [ -n "$AGENT_PID" ]; then
        # Try to find socket in standard locations
        for SOCKET in /tmp/ssh-*/agent.*; do
            echo $SOCKET
            if [ -S "$SOCKET" ]; then  # Check if it's a valid socket
                # Test the socket
                SSH_AUTH_SOCK=$SOCKET ssh-add -l >/dev/null 2>&1
                if [ $? -ne 2 ]; then  # Exit code 2 means socket is invalid
                    echo "Found socket $SOCKET"
                    export SSH_AUTH_SOCK=$SOCKET
                    export SSH_AGENT_PID=$AGENT_PID
                    return 0
                fi
            fi
        done
    fi
    return 1
}

echo "Try to find existing agent first"
if ! find_ssh_agent; then
    echo "If no agent found, start a new one"
    eval "$(ssh-agent)" > /dev/null
fi

echo "Check if keys are already added"
ssh-add -l > /dev/null 2>&1
if [ $? -eq 1 ]; then
    echo "No identities found, add default keys"
    ssh-add
fi

I saved this in file called ~/.loadkeys.sh and run it every time I start a new terminal.

Image is from Pexels.