January 01, 2017

Quickly Switch GitHub Remote Protocol

Happy New Year, everyone. I’ll keep it short today. I wrote a little shell function to help me switch my GitHub repo remote URLs between protocols. As you know, GitHub has two methods of access, HTTPS and SSH. Sometimes you’ll clone a repo using one protocol but want to use the other one. This nifty script will handle that for you.

# Basic shell function to switch your GitHub repo
# remote URL from (https|ssh) to (ssh|https) respectively.
# Tested with zsh and zprezto on macOS 10.12
github_ssh_to_https (){
URL_PART=$("grep" "-Eo" "([A-z0-9-]+\/[A-z0-9-]+.git)" <<< $1)
# echo $URL_PART
NEW_URL="https://github.com/"
NEW_URL+=$URL_PART
# echo $NEW_URL
git remote remove origin
git remote add -mt origin $NEW_URL
}
github_https_to_ssh(){
URL_PART=$("grep" "-Eo" "([A-z0-9-]+\/[A-z0-9-]+.git)" <<< $1)
# echo $URL_PART
NEW_URL="[email protected]:"
NEW_URL+=$URL_PART
# echo $NEW_URL
git remote remove origin
git remote add -mt origin $NEW_URL
}
github_remote_switch (){
URL=$(git remote -v | tail -1 | awk '{ print $2 }')
if [[ $URL == https* ]]
then
github_https_to_ssh $URL
echo "Switched your GitHub repo to use ssh remote."
else
github_ssh_to_https $URL
echo "Switched your GitHub repo to use https remote."
fi
}

You can place the above code into your dotfiles for quick use. I have mine in .zshrc. Then, simply run github_remote_switch inside your git repo folder, and the script will switch the protocol around for you.

No warranty, but it was tested working on zsh on macOS 10.12. It’s basic bash so it should be portable across UNIX-like systems.

Let me know how it works out for you!