Skip to content

Instantly share code, notes, and snippets.

@dnedrow
Last active February 13, 2019 13:59
Show Gist options
  • Select an option

  • Save dnedrow/4467592b0d8ecd7260451e7b01bf4f12 to your computer and use it in GitHub Desktop.

Select an option

Save dnedrow/4467592b0d8ecd7260451e7b01bf4f12 to your computer and use it in GitHub Desktop.
Script to create a new git branch from a given repo/branch
#!/bin/zsh
# If necessary, adjust the above to point to your ZSH executable.
# Script to create a new git branch from a given repo/branch
# Written by David E Nedrow
# Last updated 2019-02-13 00:42 Eastern
# Check for the most recent version at:
# https://gist.github.com/dnedrow/4467592b0d8ecd7260451e7b01bf4f12
local base="upstream/develop"
local newbranchname=$( date "+%Y%m%d-%H%M%S" )
vared -p "Enter the repo/branch to branch from: " base
vared -p "Enter your local branch name: " newbranchname
if [[ $base == "origin/develop" ]]; then
print -P "%B%F{red}Never branch from origin/develop.%f"
print -P "%B%F{yellow}If you want to branch from develop, always use upstream/develop."
print -P "Try again.%f"
exit 1
fi
git checkout "$base" &>/dev/null
# Did the checkout succeed? If not, error and exit.
if [[ $? -ne 0 ]]; then
print -P "%B%F{red}'$base' is not a valid repository branch.%f"
print -P "%B%F{yellow}Please try again.%f"
exit 2
fi
git checkout -b "$newbranchname" &>/dev/null
# Did the local branch creation succeed.
if [[ $? -ne 0 ]]; then
print -P "%B%F{red}Unable to create new branch $newbranchname.%f"
print -P "%B%F{yellow}Please try again.%f"
exit 3
fi
git push --set-upstream origin "$newbranchname" &>/dev/null
# Did the local branch creation succeed.
if [[ $? -ne 0 ]]; then
print -P "%B%F{red}Git push to origin/$newbranchname failed.%f"
print -P "%B%F{yellow}Please try again.%f"
exit 4
fi
print -P "%B%F{green}Successfully created and pushed %F{yellow}origin/$newbranchname%F{yellow}.%f\n"
if [[ $base == "upstream/develop" ]]; then
print -P "%B%F{green}Because you branched from %F{yellow}$base%F{green}, you should regularly merge%f"
print -P "%B%F{yellow}$base%F{green} into your new %F{yellow}$newbranchname%F{green} branch.%f\n"
print -P "%B%F{red}NEVER%F{green} merge %F{yellow}origin/develop%F{green} into $newbranchname%f."
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment