Skip to content

Instantly share code, notes, and snippets.

@sankalp-khare
Last active October 29, 2022 07:16
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save sankalp-khare/11356560 to your computer and use it in GitHub Desktop.
Save sankalp-khare/11356560 to your computer and use it in GitHub Desktop.
Changes the git url type from https to ssh or vice versa
#!/usr/bin/env bash
# Utility to change the connection method for a git repo.
# === Colour Definitions ===
red='\e[0;31m'
green='\e[0;32m'
purple='\e[0;35m'
orange='\e[0;33m'
# No Color, i.e. turn off color
nc='\e[0m'
# https://github.com/foo/bar.git
# git@github.com:foo/bar.git
# git@gist.github.com:a9713f03f27ee35f0ee6.git
# https://gist.github.com/1ed86a70d4140bdf0e5c.git
# ssh url pattern : git@<website>:<gitpath>
# https url pattern : https://<website>/<gitpath>
function print_usage(){
echo -e "${red}Usage:${nc} $0 --to-ssh ${orange}# converts https url to ssh url${nc}"
echo -e " $0 --to-https ${orange}# converts ssh url to https url${nc}"
}
function in_gitdir(){
# check if in a git repo directory
git branch &>/dev/null
if (( $? == 0 ))
then
return 0
else
return 1
fi
}
function convert_to_ssh(){
sed -r -i 's:https\://([^/]+)/(.*\.git):git@\1\:\2:g' $(git rev-parse --git-dir)/config
}
function convert_to_https(){
sed -r -i 's:git@([^/]+)\:(.*\.git):https\://\1/\2:g' $(git rev-parse --git-dir)/config
}
function main(){
if [ in_gitdir ]
then
if [[ "$1" == "to-ssh" ]]
then
convert_to_ssh
else
convert_to_https
fi
else
print_usage
exit 3
fi
}
if [ -z "$1" ]
then
print_usage
exit 1
elif [[ "$1" == "--to-ssh" ]]
then
main "to-ssh"
elif [[ "$1" == "--to-https" ]]
then
main "to-https"
else
print_usage
exit 2
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment