Git: merging specific files from another branch
Jason Rudolph has a great blog post on merging files from one branch to another in git. In most cases you probably want to cherry-pick commits, however for a quick and fast solution this is pretty cool:
$ git branch * master twitter_integration $ git checkout twitter_integration app/avatar.rb $ git status # On branch master # Changes to be committed: # (use "git reset HEAD <file>..." to unstage) # # new file: app/models/avatar.rb # $ git commit -m "'Merge' avatar code from 'twitter_integration' branch" [master]: created 4d3e37b: "'Merge' avatar code from 'twitter_integration' branch" 1 file changed, 72 insertions(+), 0 deletions(-)
Two things i noticed about this method:
- Wildcards and directories work too. So instead of getting a single file from another branch you can also do a git checkout branch * or git checkout branch path/to/directory
- All paths are relative, so if you’re not in the root of a repo, you need to give the relative path to your file(s).
Anonymous
How is master:app/avatar.rb checked out as twitter_integration:app/models/avatar.rb ?
gituser
It’s not merging the file. It just replaces/overwrites the file.
Anonymous
it is replacing the file not merging
Anonymous
git checkout –patch twitter_integration app/avatar.rb
^— this will handle the situation where avatar.rb already exists in the current branch, and allow interactive merging
Anonymous
What about removed files?
jmcmillan
Thanks for this – I love it when the first google search is exactly the answer you wanted (How can I checkout just a specific file/folder from another branch?)
Thanks for sharing this.
Guilherme
thanks a lot
Awesome Post and very helpful
Thank You
smilyanp
This has been very useful for our team, thanks for sharing!
Anonymous
This won’t merge the file, it will replace it instead.
Anonymous
Be aware. It will overwrite the existing files. So its not a merge. If we use this we should be again carefully check and revert back few parts of the file.