Skip to content

Instantly share code, notes, and snippets.

@internalsystemerror
Last active September 19, 2022 13:57
Show Gist options
  • Save internalsystemerror/218be316bdcb3950525adb2263a17e46 to your computer and use it in GitHub Desktop.
Save internalsystemerror/218be316bdcb3950525adb2263a17e46 to your computer and use it in GitHub Desktop.
Switch to the default branch of a specified remote git repository
#!/usr/bin/env bash
set -e
USAGE="Usage:
git-checkout-default <remote>"
# show help if requested
if [ "x$1" == "x-h" ] || [ "x$1" == "x-?" ] || [ "x$1" == "x--help" ]; then
echo "Switch to the default branch of a specified remote git repository."
echo "$USAGE"
exit 0
fi
# assert remote supplied
if [ "x$1" == "x" ]; then
echo "No remote given, 'git-checkout-default -h' for help"
echo "$USAGE"
exit 1
fi
# find default branch for remote
git fetch "$1"
BRANCH=$(git remote show "$1" | sed -n '/HEAD branch/s/.*: //p')
if [ "x$BRANCH" == "x" ]; then
echo "No branch found for $1"
echo "$USAGE"
exit 1
fi
# switch branch to default
if $(git show-ref --verify --quiet refs/heads/"$BRANCH"); then
git switch "$BRANCH"
exit 0
fi
git switch -c "$BRANCH" "$1"/"$BRANCH"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment