How to Get One File from Another Branch in Git


How can we checkout a single file from another branch into our current branch in Git?

Suppose we have a branch dev and another branch feature.

We want to pull index.js from feature into dev (assume it’s at the root of the project).

Get a file using git checkout

First, we’ll want to ensure we’re on the branch that will retrieve the file.

Then, we’ll want to use git checkout to obtain the file from the other branch.

git checkout dev
git checkout origin/feature -- index.js                

The double dash -- is optional but avoids confusion. For instance, git checkout -- index.js means “checkout file index.js from HEAD” (i.e. overwrite local changes), while git checkout index.js could also mean “checkout branch index.js.

Get a file using git restore

We can obtain the same functionality using git switch and git restore.

We’ll switch to the branch, then restore the correct file.

git switch dev
git restore --source feature -- index.js

Get a file using git show

Similarly, we can use git show; however, we need to specify the entire path from the root directory of the repo to the file we’d like to retrieve.

git switch dev
git show feature:path/to/index.js > path/to/index.js