Skip to content

Instantly share code, notes, and snippets.

@heuristicus
Last active March 5, 2021 11:54
Show Gist options
  • Save heuristicus/1c10939bdaddbdb32bd99d899bead1b7 to your computer and use it in GitHub Desktop.
Save heuristicus/1c10939bdaddbdb32bd99d899bead1b7 to your computer and use it in GitHub Desktop.
Try to get a git repository as written, but if the clone fails, check if it's an ssh clone and if so try again with a https clone
# You may prefer to use ssh -A if the reason you need to use this script is because the machine you are cloning on
# doesn't have access to private repositories. This will use ssh credentials from your machine rather than the local ones.
function get_repo() {
# Try to clone the repository as given, but if it fails, check if the url was via ssh, and try to clone
# with https instead. This is useful if you don't have an ssh key with access to private repositories, but do
# have credentials
# Use $@ to make sure we catch stuff like -b branch_name and so on
git clone "$@"
# If the command fails, maybe it's because of ssh. Check if the repo string $1 contains "git@"
# if so, the repo is an ssh repo
# Be explicit about concatenating all the args with $* (https://github.com/koalaman/shellcheck/wiki/SC2199)
if [ $? -ne 0 ] && [[ "$*" == "git@"* ]]; then
# replace the colon between the website and the repo details first, then git@ with https://
colon_rep="${@//:/\/}"
https_url="${colon_rep//git@/https:\/\/}"
# Attempt to clone the https url instead
echo "Looks like $1 was an ssh repo. Trying to clone with https instead ($https_url)."
# Deliberately do not use quotes here, they cause clones with extra arguments to fail
git clone $https_url
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment