SSH key not working on git bash after closing and opening new

Viewed 13381
3 Answers

You would need to auto add the ssh key to every session when you open Git Bash. For that, if you are on Windows, follow the below steps :

  • Go to the location of Git installation (usually at C:\Program Files\Git\etc\ssh)
  • Edit the ssh_config file and add the line IdentityFile Drive:\path\to\key where Drive:\path\to\key should specify the local path to your key that you have generated earlier, and save the file after editing.

Now every time you open Git Bash, the key would automatically be added to the ssh session and you will not need to add the ssh key everytime.

No matter what operating system version you run you need to run this command to complete setup:

$ ssh-add -K ~/.ssh/id_rsa

You can follow the below steps if you have to add the key each time you start a new bash session.

  1. After generating the key and adding it to the .ssh/ folder(if you have doubt in generating the public and private keys you can refer to this link from git documentation [key-gen]).
  2. The Bash profile is a file on your computer that Bash runs every time a new Bash session is created hence you can start and add the key everytime by using this bash profile in your system.
  3. Edit .bash_profile of your git bash using the below script. Add this to your .bash_profile
    #!/bin/bash
    eval `ssh-agent -s`
    a=$?
    if [ $a == 0 ]
    then
        ssh-add ~/.ssh/"<yoursshkeyfile>"
        b=$?
        if [ $b == 0 ]
        then
            echo "------------------key added-----------------"
        else
            echo "--------------key not added but agent started----------"
        fi
    else
        echo "----------------agent not started---------------"
    fi

This basically starts and adds your key everytime you open the bash. eval ssh-agent -s starts the agent and ssh-add ~/.ssh/"<yoursshkeyfile>" (add the private key file and not the public) adds your key present in ./ssh directory. "$?" this is just to check the exit status of the command executed before. This returns 0 if executed without error.

Related