Why does "git stash pop" right after "git stash --keep-index" result in conflicts?

StackOverflow https://stackoverflow.com/questions/20681448

  •  19-09-2022
  •  | 
  •  

Question

I did:

$ git stash --keep-index
$ git stash pop

and Git asks me to solve conflicts.

Do I do something wrong? How can I stash unstaged files (test the programm) and then return everything back (so I've got all staged files untouched and unstaged files are back and are unstaged)?

Was it helpful?

Solution

The problem comes from the --keep-index. The changes you stashed are in conflicts with the changes you already staged.

Here are commands you can use to reproduce

echo bar > foo
git add foo
echo baz > foo
git stash --keep-index
git stash pop #CONFLICT

In that case git doesn't know whether bar or baz should be present in foo...

The solution would be not to use the --keep-index argument or to commit the changes you added first (you can always amend your commit later)

You can also get your working directory in the same state that before using git stash branch <branchname> (you will then have to merge the branch)

OTHER TIPS

git stash saves the transition from the HEAD state to the working tree state. It also sets the working tree to the HEAD state.

git stash --keep-index saves the transition from the HEAD state to the working tree state. It also sets the working tree to the index state.

git stash pop applies the last saved transition. So if the working tree was not in HEAD state (like after git stash --keep-index), there will be a conflict. You can execute git reset --hard to set the working tree to the HEAD state before executing git stash pop to avoid it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top