alexenko
alexenko

Reputation: 3253

Git: copy all files in a directory from another branch

How do I copy all files in a directory from another branch? I can list all of the files in that directory by doing

git ls-tree master:dirname

I can then copy all of the files individually by doing

git checkout master -- dirname/filename

However, using wildcards has so far been a total fail. This does nothing:

git checkout master -- dirname/*.png

Though I guess I can use a bash script to do that, there has to be an easier way, right?

Upvotes: 295

Views: 190096

Answers (5)

shizzhan
shizzhan

Reputation: 91

git checkout sourceBranchName :

can checkout everything (root directory) from sourceBranch to your local current branch.

I tested by myself.

Upvotes: 2

Jackkobec
Jackkobec

Reputation: 6755

In my case this simplest solution to get files from the origin branch directory was:

  • origin - remote repository alias(origin by default) sourceBranchName
  • branch with required files in directory
  • sourceBranchDirPath - relative/absolute path to the required directory with

files

git checkout origin/sourceBranchName -- sourceBranchDirPath

Example:

git checkout origin/validation_fix -- src/test/java/validation/

Result was all files from origin/validation_fix branch by src/test/java/validation/ relative path in the draft mode(uncommited)

Upvotes: 10

simleo
simleo

Reputation: 2985

To copy the directory without tracking it:

git restore --source master dirname

Upvotes: 27

test30
test30

Reputation: 3654

If there are no spaces in paths, and you are interested, like I was, in files of specific extension only, you can use

git checkout otherBranch -- $(git ls-tree --name-only -r otherBranch | egrep '*.java')

Upvotes: 20

CB Bailey
CB Bailey

Reputation: 793027

As you are not trying to move the files around in the tree, you should be able to just checkout the directory:

git checkout master -- dirname

Upvotes: 449

Related Questions