Skip to content

Instantly share code, notes, and snippets.

@Ronin1702
Last active September 3, 2023 08:24
Show Gist options
  • Select an option

  • Save Ronin1702/059c47ba19d34e5174cdb5e80cec78fb to your computer and use it in GitHub Desktop.

Select an option

Save Ronin1702/059c47ba19d34e5174cdb5e80cec78fb to your computer and use it in GitHub Desktop.
PC Bash Shell Authentication for `Git` commands

Having to enter passwords for each git pull and git push command is very time consuming when you use Git Bash on PC

PowerShell on PC does not have this problem where the user set the running environment for SSH Agent:

Start-Service ssh-agent
ssh-add "$env:USERPROFILE\.ssh\id_ed25519"
  • When I use the Git Bash program on PC, though I have set up SSH key correctly, each time I must type in password when I git pull or git push.

  • When I reopen VS Code or Git Bash, the below command will return The agent has no identities. message.

    ssh-add -l
  • So that each time I have to add the SSH key to the agent again by the command below:

    eval $(ssh-agent -s)

    and then

    ssh-add ~/.ssh/id_ed25519
  • To fix this I learn that I can create or modify the .bashrc aka Bash Shell Profile to tell Git Bash to run a script each time I open a new Git Bash terminal automatically.

  • Create a .bashrc file in your Home directory, open it and paste the script below via VS Code:

    # Start SSH agent and add key, if not already running
    if ! [ -x "$(command -v ssh-agent)" ]; then
      echo 'Error: ssh-agent is not installed.' >&2
    else
      agent_running=false
    
      if [ "$SSH_AUTH_SOCK" ]; then
        # Check if the agent can be accessed by running a dummy command
        ssh-add -l > /dev/null 2>&1
        if [ $? -eq 0 ]; then
          agent_running=true
        fi
      fi
    
      if [ "$agent_running" = "false" ]; then
        eval $(ssh-agent -s)
        ssh-add ~/.ssh/id_ed25519
      fi
    fi
  • IMPORTANT Once the file is saved in your root directory, you'll need to source the .bashrc file in your Git Bash terminal by the command below:

    source ~/.bashrc
  • Now you only need to enter password the first time you open the Git Bash terminal until you close it again.

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