14

I have a git repo that I want to do a pull from. I do a normal git pull with no problems. The issue is that I want just one certain directory out of the repo. My thinking was that I could use a .gitignore file with a rule like this:

#Ignore all files
/
#Except the one I want
!/temp

The problem is this doesn't work. Is that the right way to do it or is there a better way?

c00kiemon5ter
  • 16,994
  • 7
  • 46
  • 48
Dan
  • 1,222
  • 2
  • 17
  • 33
  • btw, to ignore all files, I'd go with `/*` – c00kiemon5ter Apr 12 '12 at 13:22
  • 1
    Just for the record: you cannot pull only one directory. You always pull the **history**, not files or directories. Of course, you a free to _work_ only on some files. – fork0 Aug 04 '12 at 12:25
  • 1
    Possible duplicate of [How to pull specific directory with git](https://stackoverflow.com/questions/2425059/how-to-pull-specific-directory-with-git) – Suhaib Jun 25 '18 at 05:54

1 Answers1

50

git pull fetches and merges the remote branch.

.gitignore works only locally, and will hide matching entries from showing up on git status and being added to the index with git add. It's not what you want.

What you want to do, is fetch the remote branch, and from that, extract the dir/file you need.

$ git fetch <remote> <branch>
$ git checkout <remote>/<branch> -- relative/path/to/file/or/dir

the file/dir should now be in your branch and added to the index.

c00kiemon5ter
  • 16,994
  • 7
  • 46
  • 48
  • Should that say `remove` or `remote` on the 2nd line? – ingh.am Aug 04 '12 at 11:20
  • 1
    Actually, depending on your situation, this solution will not work at all. Imagine the in first command was added after the local repository was cloned: the fetched commits will not be referenced by any local branch (not even by a tracking branch like `/`). `git fetch` will store the reference in `FETCH_HEAD`. Besides, `git checkout` will just modify the local tree and index. Afterwards, you'll have no idea where all these files came from. – fork0 Aug 04 '12 at 12:30
  • No problem! I was going to edit myself but didn't try the command first! :D +1 – ingh.am Aug 04 '12 at 14:45
  • @c00kiemon5ter, Is **git checkout / -- relative/path/to/file/or/dir** same as **git merge / -- relative/path/to/file/or/dir** ? – Ninad Jul 30 '15 at 09:16
  • 2
    @Ninad: no, `git checkout` doesn't preserve history, `git merge` does. – FBB Oct 20 '15 at 16:22
  • I take it there's no way to fetch only changes to the relevant directory; all changes within each commit for the branch are fetched from the remote, even if some of those changes are checked out, right? – Andy Mar 22 '18 at 20:51