Jacopo Grassi Jacopo Grassi - 2 months ago 5x
Git Question

Git: move a branch to make it point to another

I had the following situation:


then I had to make some changes to master:

| |
branch1 master

now I want branch1 to be at the same point of master (and therefore to contain the commits I made):


I don't know if a merge would be the correct way to achieve this.
what steps should I take?

EDIT: also consider that I have uncommitted changes that should be committed on branch1 after branch1 is up to date with master. so I need the current changes to be left untouched to be committed later on branch1


Since branch1 references a commit that is an ancestor of master, a merge operation won't result in a merge commit; instead, Git will simply move the branch1 reference forward so that it references the same commit as master. This is called a fast-forward merge.

From the documentation:

When you try to merge one commit with a commit that can be reached by following the first commit’s history, Git simplifies things by moving the pointer forward because there is no divergent work to merge together – this is called a “fast-forward.”

So, in your case, you can simply say:

git checkout branch1
git merge master

which will make branch1 point to the same commit as master.

Update: note that you need to have a clean working directory before doing the merge. If you have uncommitted changes in branch1 (i.e. you have a dirty working directory), you should first store them away in the stash by using the git-stash command:

git stash save --include-untracked -m "Work in progress"

Once your changes are saved and your working directory clean, you can proceed with the merge. Afterwards, you can restore the files from the stash by saying:

git stash pop

which will put those files back in the working directory and remove them from the stash. At that point, you can choose to commit them in any numbers of commits.