5

Sometimes I find myself in the position where I want to dump everything in my working tree except for 1 or 2 files. Is there an easy way to do this? As it is I've been manually typing git checkout .... for all the files I want to checkout from the index and don't include the files I want to keep but that's pretty laborious.

Another way I could think of doing this would be to stash 1 or 2 files I want to keep, then "checkout ." then restore the stash. Would that be a good way to do this?

asolberg
  • 6,638
  • 9
  • 33
  • 46
  • Does this answer your question? [Git: Checkout all files except one](https://stackoverflow.com/questions/20008025/git-checkout-all-files-except-one) – Vinícius M Dec 21 '21 at 21:22

1 Answers1

10

I want to do the same occasionally and usually go with the following set of commands (assumes than there is nothing in the index):

git add file-to-preserve-1 file-to-preserve-2
git stash save --keep-index "Changes discarded because ..."
# git stash drop # think twice before running this command
git reset

In words:

  1. Put files you need to preserve to index.
  2. Stash everything (possibly with a meaningful message), but leave index untouched.
  3. Drop stashed changes (only if you sure they are useless).
  4. Reset the index.

Another way I can think of (didn't try it actually, the first one works fine for me):

git update-index --skip-worktree file-to-preserve-1 file-to-preserve-2
git checkout .
git update-index --no-skip-worktree file-to-preserve-1 file-to-preserve-2

Explained:

  1. Command git to ignore some files.
  2. Checkout everything in the current directory.
  3. Tell git to treat files from 1 as usual again.
xaizek
  • 5,098
  • 1
  • 34
  • 60
  • 1
    This is a good work flow, but personally I skip the `git stash drop` step. It is surprising how often you find yourself wanting the changes you just dropped; and even more surprising how often that realization comes 2 ms after you press return on the drop! – William Pursell Jul 04 '14 at 16:30
  • @WilliamPursell, you're right, edited a bit. Good thing is that git prints hash of dropped stash on the screen, the most important then is to do not lose this information. – xaizek Jul 04 '14 at 16:33
  • 1
    You can give the stash a useful message, eg. `git stash save --keep-index discard-reason` – Useless Jul 04 '14 at 17:30
  • @Useless, good point, edited. I always promise myself to give useful messages to stash items, but end up with tenth of them all named like `WIP on ...` ... – xaizek Jul 04 '14 at 17:33