Skip to content

Instantly share code, notes, and snippets.

@OndraZizka
Last active September 8, 2023 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OndraZizka/2a2b167225b3f4e05a4ae3c4796432fd to your computer and use it in GitHub Desktop.
Save OndraZizka/2a2b167225b3f4e05a4ae3c4796432fd to your computer and use it in GitHub Desktop.
Git: Rebase a (sub)branch from one base to another, leaving the other base's commits.
#!/bin/bash
## Places a branch to a new base.
## Useful when splitting a long branch to multiple pull requests.
##
## ---+--------master
## \
## --- A ---- B
##
## git-moveBranch.sh B from A to master
##
## ---+-------- master ---- B
## \
## --- A
## Also, this can be used to split long branches into smaller pull requests.
## Imagine you have a long branch X
##
## main ---------------X
##
## which you split to smaller MRs:
##
## MR #1 with branch X1.
## MR #2 with branch X2.
##
## main --------X1-----X2
##
## It is very important to mention in MR #2 that it depends on MR #1.
## Gitlab allows to even prevent MR #2 from being merged before MR #1.
##
## Then, when MR 1 / X1 gets merged, you may run:
##
## $ git co main && git pull
##
## $ git-moveBranch.sh X2 from X1 to main
##
## That will move all commits of X2, and none from X1, onto main, which already includes X1.
##
## mainOld---------main-----X2
##
function printUsageAndExit() {
echo "Usage:";
echo " `basename $0` <branch> from <previous-base> to <new-base>";
echo
git branch;
exit 1;
}
if [ 5 != $# ] ; then printUsageAndExit; fi
if [ "$2" != "from" ] ; then printUsageAndExit; fi
if [ "$4" != "to" ] ; then printUsageAndExit; fi
WHAT="$1"
FROM="$3"
ONTO="$5"
echo "Running: git rebase —-onto=\"$ONTO\" \"$FROM\" \"$WHAT\""
# git rebase —-onto <place-to-put-it> <last-change-that-should-NOT-move> <branch to move>
git rebase --onto "$ONTO" "$FROM" "$WHAT"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment