Copy files from another branch with Git


Welcome to the next pikoTutorial!
What's the problem?
Imagine that you are working on a feature branch called _targetbranch and someone else commits some folder to another feature branch called _sourcebranch. You need this folder, but these are completely different branches, with different changes and diverged history, so you can't just rebase or merge changes from _sourcebranch. Often in such situation I see people doing something like this:
- commit changes to _targetbranch
- checkout to _sourcebranch
- copy the required folder to some backup directory
- checkout to _targetbranch
- copy the required folder from the backup directory into the repository
- delete the required folder from the backup directory
How to make it faster?
All these 6 steps mentioned above may be executed with just a single Git command:
git checkout source_branch -- path/to/folder
After that, you should see the required folder on your branch.
Note for beginners: remember that the copied folder won't be automatically committed!
Subscribe to my newsletter
Read articles from pikoTutorial directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
