Skip to content

Instantly share code, notes, and snippets.

@withakay
Created June 20, 2023 08:21
Show Gist options
  • Save withakay/6f3f17e2e1528a1491660c171b7c97e3 to your computer and use it in GitHub Desktop.
Save withakay/6f3f17e2e1528a1491660c171b7c97e3 to your computer and use it in GitHub Desktop.
Git checkout default branch and pull. Optionally create a new working branch
#!/bin/bash
# Place this script in your path and make it executable
# Display the script's usage
display_usage() {
echo "Git Checkout Default Script"
echo "This git script will check out the default HEAD branch"
echo "and pull the latest from the remote. Optionally it will"
echo "create a new branch ready for you to work on."
echo "Usage: git cod [options]"
echo "Options:"
echo " -b, --branch <branch-name> Checkout a new branch"
echo " -h, --help Display this help message"
}
# Get the HEAD branch name from the Git remote show command
# Typically this will be 'main' or 'master'
branch=$(git remote show origin | grep HEAD | awk '{print $NF}')
# Checkout the branch
git checkout $branch
# Pull the latest changes from the remote repository
git pull origin $branch
# Check if any arguments are provided
if [[ $# -eq 0 ]]; then
# No arguments provided, proceed with the default behavior
echo "No additional options provided."
elif [[ "$1" == "-h" || "$1" == "--help" ]]; then
# Display help message
display_usage
exit 0
elif [[ "$1" == "-b" || "$1" == "--branch" ]]; then
# Check if a branch name is provided after the parameter
if [[ -z "$2" ]]; then
echo "Error: No branch name provided."
exit 1
fi
# Checkout a new branch
git checkout -b $2
else
# Invalid option provided
echo "Invalid option: $1"
echo "Use --help to display usage."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment