Search code examples
gitgithubversion-controlbitbucketdvcs

Merge part of a branch into master with git


I'll explain my scenario:

  1. I have two git branches say master, branch1
  2. My master branch has following files and commits associated with it - it's like after each file i created i did git commit:

    master-file1.html has masterfile1-commit-message
    master-file2.html - masterfile2-commit-message
    master-file3.html - masterfile3-commit-message
    
  3. My branch1 branch has following files and commits associated with it:

    branch1-file1.html has branch1file1-commit-message
    branch1-file2.html - branch1file2-commit-message
    branch1-file3.html - branch1file3-commit-message
    branch1-file4.html - branch1file4-commit-message
    branch1-file5.html - branch1file5-commit-message
    

So i don't want to merge branch1 completely to master branch, i just want partial merge. So at the final i want is something like this:

  1. My master branch should be like this:

    master-file1.html has masterfile1-commit-message
    master-file2.html - masterfile2-commit-message
    master-file3.html - masterfile3-commit-message
    branch1-file1.html has branch1file1-commit-message
    branch1-file2.html - branch1file2-commit-message
    
  2. My branch1 branch should be unchanged:

    branch1-file1.html has branch1file1-commit-message
    branch1-file2.html - branch1file2-commit-message
    branch1-file3.html - branch1file3-commit-message
    branch1-file4.html - branch1file4-commit-message
    branch1-file5.html - branch1file5-commit-message
    

Can i achieve this in git? If so then how?


Solution

  • First, find the SHA1 hash for the commit with branch1-file2.html. You can do this with the following commands:

    git checkout branch1
    git log --oneline
    

    Look for the hex string at the beginning of each line. Now once you have the hash, just merge master to it:

    git checkout master
    git merge <SHA1 hash>