jpmelos jpmelos - 2 months ago 6
Git Question

How can I discard only the changes not in the staging area?

How can I discard only the changes not in the staging area?

Suppose:

$ cat file.txt
Hello
$ git add file.txt
# edit file.txt
$ cat file.txt
Hi


How do I get the contents of
file.txt
to what it was before the last edit and after the
git add
command without editing it back manually?

Real case scenario is I have these files which are programatically generated but must be committed to the repository (e.g., Django migrations). I want to regenerate the files, but only commit some of the changes made. So I use
git add -p
to select the changes I want, and then I want to discard the changes not selected.

Answer

To revert (to discard the modifications in) a specific file x:

git checkout x

To revert all the modified files after the last git pull command:

git checkout .

Otherwise, you can discard the unstaged changes:

git stash save --keep-index --include-untracked
git stash drop