Skip to content

Instantly share code, notes, and snippets.

@donaldducky
Created July 8, 2011 17:23
Show Gist options
  • Select an option

  • Save donaldducky/1072311 to your computer and use it in GitHub Desktop.

Select an option

Save donaldducky/1072311 to your computer and use it in GitHub Desktop.
Create a new git branch based off the current branch
#!/bin/bash
# Find the current branch
function git_branch() {
git branch 2> /dev/null | grep ^* | cut -c 3-
}
# Find the current remote
function git_remote() {
if [ -z "$1" ]; then
return 0
fi
local git_repo=$1
local git_config=$(git rev-parse --show-toplevel)/.git/config
cat $git_config | grep "\"$git_repo\"" -A 2 | grep remote | cut -d ' ' -f 3
}
CURRENT_BRANCH=$(git_branch)
if [ "$CURRENT_BRANCH" = "" ]; then
echo "You are not in a git repository"
exit 1
fi
CURRENT_REMOTE=$(git_remote $CURRENT_BRANCH)
if [ "$CURRENT_REMOTE" = "" ]; then
echo "Could not locate remote for the branch $CURRENT_BRANCH"
exit 1
fi
if [ $# -gt 0 ]; then
if [ $2 ]; then
REMOTE=$2
else
REMOTE=$CURRENT_REMOTE
fi
echo -n "Create branch [$REMOTE/$1] based from [$CURRENT_REMOTE/$CURRENT_BRANCH]? (y/n) "
read confirm
if [ `echo $confirm | tr [:upper:] [:lower:]` = 'y' ]; then
git push $REMOTE $CURRENT_REMOTE/$CURRENT_BRANCH:refs/heads/$1
git branch --track $1 $REMOTE/$1
echo "Done creating branch $REMOTE/$1."
else
echo "Branch $REMOTE/$1 creation cancelled."
fi
else
echo "Usage:"
echo "$(basename $0) <branch-name> [ <remote-name> ]"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment