SSH keys and git bash

So when it comes to git I much prefer ssh over https. I can’t clearly articulate why, I just do. However one thing I noticed is that git bash was constantly asking me for the password for my ssh key. It got annoying so I did a little research and found a GitHub help page with the answer. It’s kind of hard to find on that page, so I pulled it out here.

The trick is to use a .bashrc file. It will run automatically every time you open gitbash. You will get asked for your ssh key password once at the very beginning and that is it. It will be cached and then used whenever needed. The downside is you will get asked every time the shell starts. If you are only working locally and therefore don’t need your key and don’t want to type in your password, ctl +c will cancel the caching and return you to a prompt.

Once the .bashrc file is in place, you will automatically be prompted to enter your credentials for your ssh key. After that it will be cached as long as the shell window is open and you won’t be asked again.

All you need to do is create a file with the content below, name it .bashrc and drop into your home directory (~). If the file already exists, you can just add the content to what is already there. I literally just copied this from the GitHub page so don’t ask me too many questions about how it works. All I can say is “Works on my machine.”

Here is the content:

env=~/.ssh/agent.env

agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }

agent_start () {
    (umask 077; ssh-agent >| "$env")
    . "$env" >| /dev/null ; }

agent_load_env

# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)

if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
    agent_start
    ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
    ssh-add
fi

unset env

Leave a Reply

Your email address will not be published. Required fields are marked *

*