Skip to content

Instantly share code, notes, and snippets.

@lbussy
Last active August 6, 2021 11:20
Show Gist options
  • Save lbussy/7f96a137d40e3074cacd2fc0732dabd0 to your computer and use it in GitHub Desktop.
Save lbussy/7f96a137d40e3074cacd2fc0732dabd0 to your computer and use it in GitHub Desktop.
Change Git to Use SSH

Change Git to Use SSH

Here's how to change git to use SSH.

The below scripts will automate the repo changes needed.

#!/bin/bash
# Modified from: https://gist.github.com/m14t/3056747
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="git@github.com:$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"
eval "$CHANGE_CMD"
echo "Success"
#!/bin/bash
# Modified from: https://gist.github.com/chuckbjones/9dc6634fe52e56ba45ac
#origin or upstream
REMOTE=${1-origin}
REPO_URL=$(git remote -v | grep -m1 "^$REMOTE" | sed -Ene's#.*(git@github.com:[^[:space:]]*).*#\1#p')
if [ -z "$REPO_URL" ]; then
echo "-- ERROR: Could not identify Repo url."
echo " It is possible this repo is already using HTTPS instead of SSH."
exit
fi
USER=$(echo "$REPO_URL" | sed -Ene's#git@github.com:([^/]*)/(.*).git#\1#p')
if [ -z "$USER" ]; then
echo "-- ERROR: Could not identify User."
exit
fi
REPO=$(echo "$REPO_URL" | sed -Ene's#git@github.com:([^/]*)/(.*).git#\2#p')
if [ -z "$REPO" ]; then
echo "-- ERROR: Could not identify Repo."
exit
fi
NEW_URL="https://github.com/$USER/$REPO.git"
echo "Changing repo url from "
echo " '$REPO_URL'"
echo " to "
echo " '$NEW_URL'"
echo ""
CHANGE_CMD="git remote set-url $REMOTE $NEW_URL"
eval "$CHANGE_CMD"
echo "Success"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment