Skip to content

Instantly share code, notes, and snippets.

@f4th4n
Created May 4, 2025 06:22
Show Gist options
  • Save f4th4n/c8ccf8a197067a3b95d521724ba4a866 to your computer and use it in GitHub Desktop.
Save f4th4n/c8ccf8a197067a3b95d521724ba4a866 to your computer and use it in GitHub Desktop.
Git Checkout main or master
#!/bin/bash
# This script checks if the 'main' branch exists in the current Git repository.
# If 'main' exists, it checks out the 'main' branch.
# If 'main' does not exist, it checks out the 'master' branch.
# Check if the 'main' branch exists
# git rev-parse --verify <branch_name> returns 0 if the branch exists, non-zero otherwise.
if git rev-parse --verify main >/dev/null 2>&1; then
echo "Branch 'main' exists. Checking out 'main'..."
git checkout main
if [ $? -eq 0 ]; then
echo "Successfully checked out 'main'."
else
echo "Error checking out 'main'."
exit 1
fi
else
# If 'main' does not exist, check out 'master'
echo "Branch 'main' does not exist. Checking out 'master'..."
# Check if 'master' branch exists before attempting to checkout
if git rev-parse --verify master >/dev/null 2>&1; then
git checkout master
if [ $? -eq 0 ]; then
echo "Successfully checked out 'master'."
else
echo "Error checking out 'master'."
exit 1
fi
else
echo "Neither 'main' nor 'master' branches exist in this repository."
exit 1
fi
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment