[git] Force git stash to overwrite added files

I have some files which were untracked in git. I made some changes and wanted to commit them, but realised I had forgotten to check in the unmodified files first. So I stashed the files, then added the unmodified versions.

Then when I apply the stash to the repository, I get conflicts due to the files having already been added.

How can I apply the stash, and force the versions in the stash to be used in preference to the originals in the repository?

Thanks

This question is related to git

The answer is


Use git checkout instead of git stash apply:

$ git checkout stash -- .
$ git commit

This will restore all the files in the current directory to their stashed version.


If there are changes to other files in the working directory that should be kept, here is a less heavy-handed alternative:

$ git merge --squash --strategy-option=theirs stash

If there are changes in the index, or the merge will touch files with local changes, git will refuse to merge. Individual files can be checked out from the stash using

$ git checkout stash -- <paths...>

or interactively with

$ git checkout -p stash

git stash show -p | git apply

and then git stash drop if you want to drop the stashed items.


TL;DR:

git checkout HEAD path/to/file
git stash apply

Long version:

You get this error because of the uncommited changes that you want to overwrite. Undo these changes with git checkout HEAD. You can undo changes to a specific file with git checkout HEAD path/to/file. After removing the cause of the conflict, you can apply as usual.


To force git stash pop run this command

git stash show -p | git apply && git stash drop