git stash apply/pop, but forgot --index

Viewed 42

Situation:

  • local git checkout of branch main with both staged and non-staged changes
  • git stash
  • ... work on other branches, etc ...
  • git checkout main
  • git stash apply <- NOTE the accidentally missing --index

How can I now (without major git surgery...) recover the missing staged changes, i.e. the state if I would have gotten, had I correctly used git stash apply --index above?

And, ideally, I don't want to re-resolve any conflicts already dealt with after the problematic git stash apply command.

2 Answers

Your problem is that right now your staged changes are mixed with the stashed changes and you want to separate them. Do the following:

  1. commit all your changes in one commit on main branch git add -A && git commit -m "Save stash mixed with staged"
  2. go back once without hard resetting the HEAD git checkout HEAD~1
  3. create a temp branch git checkout -b temp
  4. Get your stashed changes on this temp branch git stash apply
  5. commit the stashed changes on this branch git add -A && git commit -m "Save stashed changes temporarily"
  6. Get your staged changes now git reset --soft main
  7. Now you have your staged changes visible in front of you, so stash them git stash save "staged_changes"
  8. Go back to main git checkout main
  9. git reset --hard HEAD~1
  10. git stash pop and your staged changes will be visible again

I hope this helps ;)

For a stash named stash@{0}, do:

git read-tree stash@{0}^2

This changes only the index (aka. staging area), so git reset will 'undo' it.

Related