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 target_branch and someone else commits some folder to another feature branch called source_branch. 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 source_branch. Often in such situation I see people doing something like this:

  • commit changes to target_branch
  • checkout to source_branch
  • copy the required folder to some backup directory
  • checkout to target_branch
  • 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!