How to move a branch backwards in git?

GitGithub

Git Problem Overview


The title is not very clear. What I actually need to do often is the following:

Let's say I have a development going on with several commits c1,c2,... and 3 branches A,B,C

c1--c2--c3--(B)--c4--(A,C)

Branch A and C are at the same commit.

Now I want branch A to go back where B is, so that it looks like this:

c1--c2--c3--(A,B)--c4--(C)

Important is that this has to happen locally and on GitHub.

Git Solutions


Solution 1 - Git

Use the reset subcommand:

git checkout A
git reset --hard B
git push --force github

As a sidenote, you should be careful when using git reset while a branch has been pushed elsewhere already. This may cause trouble to those who have already checked out your changes.

Solution 2 - Git

If there are no commits on branch A, then the git reset --hard B solution given by Bram Schoenmakers will work.

However if there are commits are branch A which must be preserved, then the following should do the trick:

  1. Make a backup copy of your repo (just in case)
  2. git checkout A
  3. git rebase -i --onto B SHA1-A^

...where SHA1-A^ is the commit id of the parent of your branch A

See the git rebase man page for details.

NOTE: This will rewrite history (as rebase always does). Special consideration should be made if your A branch was ever pushed to a public repo.

Solution 3 - Git

I usually use this sequence and find it the simplest way:

git checkout B
git branch -f A B

Solution 4 - Git

Delete the branch both locally and remotely, recreate the branch, push the branch back up to the server.

git branch -d A
git push origin :heads/A
git branch B A
git push origin A:A

Alternately you can use the following command to undo that last commit.

git revert c4

Which will make your timeline look like:

c1--c2--c3--(B)
             \
              c4--(C)
               \
                (^c4)--(A)

where (^c4) is a commit that undoes c4

I don't recommend using rebase or revert on a branch that has been pushed to a remote repo, they can cause tons of trouble for you or anyone else using that repo.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser89021View Question on Stackoverflow
Solution 1 - GitBram SchoenmakersView Answer on Stackoverflow
Solution 2 - GitTim HeniganView Answer on Stackoverflow
Solution 3 - GitVladyslav SavchenkoView Answer on Stackoverflow
Solution 4 - GitkubiView Answer on Stackoverflow