3

The common case is to merge a branch up to its last commit:

      A---B---C topic
     /         \
D---E---F---G---H master

But I wanted to exclude the last commit, like this:

        A---B---C topic
       /     \
  D---E---F---G  master

Is it possible to merge the topic branch into master without including topic's last commit?

4
  • git-scm.com/docs/git-merge Also, why do you have two commits with the same name? Commented Dec 8, 2013 at 2:41
  • Impossible to tell what you're asking. Do you mean you want to merge C into master without moving the branch pointer topic? What does D have to do with anything? You might have better luck if you show us before/after diagrams of what you're trying to do. Also, it's "please", not "pls". Commented Dec 8, 2013 at 2:52
  • i mean "merge B into master without C". Commented Dec 8, 2013 at 3:01
  • Wait, your "after" diagram has suddenly lost commit "H". What happened to it? Was that intentional? Commented Dec 8, 2013 at 3:05

2 Answers 2

12

When merging, you don't need to say a branch name, you just need a commit reference.

Assuming B is the penultimate commit on the branch topic, you could do:

git checkout master
git merge topic~

Where the ~ means "the commit before". You can learn more about how to reference commits with man gitrevisions.

As an alternative, you could provide the SHA1 of the commit B directly.

Sign up to request clarification or add additional context in comments.

3 Comments

git merge topic~${n} can do it. 但是如何根据SHA1来指定合并到指定的提交。
Is this answer still correct in 2021? Or do we use cherry-pick instead?
@Echoes cherry-pick <branch-name> does the opposite of what was discussed in this case (only gets the last commit). If you mean cherry-pick <penultimate-commit-sha1> instead then it does a different thing - it only gets that commit, not the whole tree. Might be what you want, but the question had a different context
4

i mean "merge B into master without C". – kangear 1 min ago

Then just do exactly that. Merge B into master. It's completely valid to merge by commit ID rather than by branch name:

$ git checkout master
$ git merge B

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.