Skip to content

Instantly share code, notes, and snippets.

@FigBug
Created January 12, 2018 17:00
Show Gist options
  • Save FigBug/b3c940d22970d84d0b0390b38fcf5c81 to your computer and use it in GitHub Desktop.
Save FigBug/b3c940d22970d84d0b0390b38fcf5c81 to your computer and use it in GitHub Desktop.
Convert git repo from https to ssh
#/bin/bash
#-- Script to automate https://help.github.com/articles/why-is-git-always-asking-for-my-password
REPO_URL=`git remote -v | grep -m1 '^origin' | sed -Ene's#.*(https://[^[:space:]]*).*#\1#p'`
if [ -z "$REPO_URL" ]; then
echo "-- ERROR: Could not identify Repo url."
echo " It is possible this repo is already using SSH instead of HTTPS."
exit
fi
USER=`echo $REPO_URL | sed -Ene's#https://github.com/([^/]*)/(.*).git#\1#p'`
if [ -z "$USER" ]; then
echo "-- ERROR: Could not identify User."
exit
fi
REPO=`echo $REPO_URL | sed -Ene's#https://github.com/([^/]*)/(.*).git#\2#p'`
if [ -z "$REPO" ]; then
echo "-- ERROR: Could not identify Repo."
exit
fi
NEW_URL="[email protected]:$USER/$REPO.git"
echo "Changing repo url from "
echo " '$REPO_URL'"
echo " to "
echo " '$NEW_URL'"
echo ""
CHANGE_CMD="git remote set-url origin $NEW_URL"
`$CHANGE_CMD`
echo "Success"
@yvs2014
Copy link

yvs2014 commented Jun 19, 2023

A very useful script, thanks

I've added into its fork

  • optional .git suffix in url (reason: a local copy is often cloned with git clone https://github.com/user/repo, i.e. without adding .git suffix)
  • omitting username in gist.github.com url (reason: to make it work with gists too)

p.s. I haven't found how to make pull-request on a gist, so that there's this comment

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