SSH Agent Config Fragment

SSH Agent

This is the fragment to make sure the ssh-agent is running when you open the terminal.

Put this in ~/.config/fish/conf.d/ssh-agent.fish.

if status is-login
    and status is-interactive
    if test -n $SSH_KEYS_TO_AUTOLOAD
        keychain --eval $SSH_KEYS_TO_AUTOLOAD | source
    else
        echo "SSH_KEYS_TO_AUTOLOAD environment variable not set"
        echo "add key-file-name(s) to this variable"
        echo "set --universal --append SSH_KEYS_TO_AUTOLOAD ~/.ssh/id_<keyid>"
    end
end

From the fish documentation for test.

-n STRING

Returns true if the length of STRING is non-zero.

I don't know why you'd use test -n instead of set -q. I suppose this allows for empty strings being set, although that seems odd…

Note: The default key type has changed so the default file name is no longer id_rsa it's id_ed25519.

Note: The Super User answer that I got this updated version from used a sentinel (status is-login and status is-interactive) to check whether to run the code block or not, but this was preventing it from ever being run when I SSH'd in so I got rid of it.

Although the name keychain makes it sound like it's a general password manager, according to the man-page it's meant specifically to manage the ssh-agent. It will check if you already have an ssh-agent running and only start one if you don't. This way you don't end up starting one for every screen you open up.

The --eval option sends the SSH-Agent message to stdout, --quiet suppresses other messages, --quick tells it to use a running ssh-agent if it finds one without verifying the keys and then we pipe it to source to load the environment.

The SSH_KEYS_TO_AUTOLOAD Variable

Note: This expects you to put the names of keys into the SSH_KEYS_TO_AUTOLOAD variable at the command line. It isn't set in the code-snippet so that you can change it/them by updating the environment variable instead of updating the file, but this means you have to remember to set it.

Add A Key

set --universal --append SSH_KEYS_TO_AUTOLOAD ~/.ssh/<key-file>

Remove A Key

set --universal --erase SSH_KEYS_TO_AUTOLOAD[<index of key>]

Links