Persisting Homebrew's ssh-agent

I've installed OpenSSH from Homebrew, because I need a newer version to support hardware keys (Big Sur comes with 8.1; 8.2+ is needed).

However, my system insists on persisting the default ssh-agent stored in /usr/bin rather than the one in /opt/homebrew/bin/ssh-agent. I can manually change over to the Homebrew agent with eval (ssh-agent -c), but this isn't persisted across new terminal sessions.

In case it matters, I'm using iTerm and fish shell. I don't simply want to put eval (ssh-agent -c) into my fish config, because then I would still have to run ssh-add -K every time I open a new terminal window with the intention of using SSH. With the bundled agent, I only have to run ssh-add once, and it persists across sessions.

How can I accomplish this?


I'm using bash here (but the procedure must be easy to port to fish, zsh or other shell)

Run cat ~/.ssh/<yourkey>.pub which outputs something like this

ssh-<krypto gibberish> <some string>

Copy a bit of the <some string> part and add below:

KEYS=$(ssh-add -L)
if [[ "$KEYS" != *"<some string>"* ]]
then
    ssh-add -K .ssh/<yourkey> [optional other keys] >/dev/null
fi

The next time you open a terminal it will check if your key is loaded, and if not, load it.

I use the above solution since I have multiple keys for work etc, and that screws up the built-in ssh-agent auto-load as well.