Skip to content

Instantly share code, notes, and snippets.

@bsara
Last active April 22, 2024 13:49
Show Gist options
  • Save bsara/5c4d90db3016814a3d2fe38d314f9c23 to your computer and use it in GitHub Desktop.
Save bsara/5c4d90db3016814a3d2fe38d314f9c23 to your computer and use it in GitHub Desktop.
Setup SSH Authentication for Git Bash on Windows

Setup SSH Authentication for Git Bash on Windows

Prepararation

  1. Create a folder at the root of your user home folder (Example: C:/Users/uname/) called .ssh.
  2. Create the following files if they do not already exist (paths begin from the root of your user home folder):
    • .ssh/config
    • .bash_profile
    • .bashrc

Create a New SSH Key

Follow the steps in the section named "Generating a new SSH Key" found in the following documentation from GitHub: Generating a new SSH key and adding it to the ssh-agent

Configure SSH for Git Hosting Server

Add the following text to .ssh/config (.ssh should be found in the root of your user home folder):

Host github.com
 Hostname github.com
 IdentityFile ~/.ssh/id_rsa

Enable SSH Agent Startup Whenever Git Bash is Started

First, ensure that following lines are added to .bash_profile, which should be found in your root user home folder:

test -f ~/.profile && . ~/.profile
test -f ~/.bashrc && . ~/.bashrc

Now, add the following text to .bashrc, which should be found in your root user home folder:

# Start SSH Agent
#----------------------------

SSH_ENV="$HOME/.ssh/environment"

function run_ssh_env {
  . "${SSH_ENV}" > /dev/null
}

function start_ssh_agent {
  echo "Initializing new SSH agent..."
  ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
  echo "succeeded"
  chmod 600 "${SSH_ENV}"

  run_ssh_env;

  ssh-add ~/.ssh/id_rsa;
}

if [ -f "${SSH_ENV}" ]; then
  run_ssh_env;
  ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
    start_ssh_agent;
  }
else
  start_ssh_agent;
fi
@m0veax
Copy link

m0veax commented Jan 24, 2023

works with a few changes for bitbucket.org too

@eutobias
Copy link

I have followed these steps, and when I start git bash, I can see it is starting the ssh-agent. But when I perform a git operation (e.g. git clone), the github login dialog pops up and it is not using the ssh key. How do I get git to use the ssh key and not the github login? On the github side, I have added the ssh key as per the github instructions..

image

you should use ssh urls of repository, not https one

@Jugarcia01
Copy link

You instructions worked perfectly for me!
Thanks bsara!!!

@md1116
Copy link

md1116 commented Nov 9, 2023

This worked well for me. Thanks for sharing

@shwetamoharil
Copy link

For windows user please add the .bash_profile and.bashrc file in your root directory if not present. And the rest steps remain the same.
Thanks for the solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment