Easy ssh-agent in bashrc

I recently started using ssh-agent again, due to enabling git-lfs in GitLab. Having LFS enabled seems to make each push and pull create multiple SSH connections, which means I have to type my ssh key passphrase multiple times in a row. This ended up being the final straw for me, and I decided to get ssh-agent working on my setup, which is primarily Tmux inside of WSL.

I wrote this simple bash script to setup the ssh-agent on login:

#!/bin/bash

function maybe_start_ssh_agent {
    local ssh_env_file="$HOME/.ssh/agent_env"

    ssh-add -l &> /dev/null
    if [[ $? -ne 2 ]]; then
        # ssh-agent already running
        return
    fi

    # try loading existing environment file
    if [[ -f "$ssh_env_file" ]]; then
        eval "$(<$ssh_env_file)" >/dev/null
    fi

    ssh-add -l &> /dev/null
    if [[ $? -ne 2 ]]; then
        # ssh-agent already running
        return
    fi

    # start a new agent if agent still not available
    ssh-agent -s > "$ssh_env_file"
}

function timed_ssh_add {
    ssh-add -t 1h
}

My .bashrc simply includes this file and calls maybe_start_ssh_agent to get things set up:

. $HOME/dotfiles/include/ssh_agent.sh
maybe_start_ssh_agent

I wrote this code inside a bash function so that I could keep the code a bit cleaner. The function can early-return so that the if blocks don’t get too nested, and variables like ssh_env_file can be made local variables to avoid polluting the shell environment. I also added a timed_ssh_add function to help me remember to set a time limit on my keys, since the same ssh-agent instance is used in every session.

Just to keep things extra tidy, I put this code in a separate file inside my dotfiles repo, which gets included from the main .bashrc.

Additional Resources

This blog post was a helpful resource, and also describes some more advanced use-cases, like multiple keys with multiple agents.