Git: checkout files or directories from another branch

You probably knew that a branch can be "checked out" with the `git checkout branch-name` command, but interestingly, a single file or a directory can also be subject to checkout.

If you want to pull a file from a feature branch to a master, the workflow would be as follows:

# First switch to the master branch
$ git checkout master

# Then grab the needed file
$ git checkout feature-branch -- src/js/some-file.js

# The thee is now dirty
$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   src/js/some-file.js

# Then commit in normal fashion
$ git commit -m "Get a file from the feature branch"

Checking out a directory:

$ git checkout feature-branch -- src/js/


  • Rahul Kant says:

    suppose I have a file name abc.js in js folder , in this file I have made some changes , but forgot to commit. And then I typed this command

    git checkout feature-branch — src/js

    this command replaces the old some-file.js with new some-file.js and abc.js file with new abc.js

    how to go back to previous state , I mean the state just before writing above command, where I can see the changes I have made to abc.js ?

  • Anonymous says:

    I think git checkout HEAD^1 should do it.

Club-Mate, the beverage →