1

I want to checkout a previous commit, but I've made changes, so it's prompting me to commit or stash the changes first. I don't have the changes at the point where I want to commit them yet. Is this what git stash would work for? Would it save my changes such that if I checkout the previous commit and then return to HEAD, finish my changes and then commit, all my changes from before and after stashing would be included in that commit?

2
  • Note you can also make a wip commit and then amend it later. Commented Apr 8, 2023 at 3:50
  • Yes, you can use git stash. And if your changes include untracked files, see How do you stash an untracked file? Commented Apr 8, 2023 at 4:24

2 Answers 2

2

Yup, that's exactly what git stash is for. It will save your changes, and you will be able to restore them later with git stash pop. (That's the simple usage. git stash pop will get the last thing you saved.)

Say you were working on main.

git stash             # Saves and removes your changes
git checkout HEAD^    # Checkout previous commit
# Play around here.
git checkout main     # Go back to the branch you were using.
git stash pop         # Restore your work.
Sign up to request clarification or add additional context in comments.

1 Comment

Expanding a little bit, you can have several different things in git stash, so git stash list will show you roughly what each is.
1

I don't have the changes at the point where I want to commit them yet.

Yes you do! You do want to create a commit, it's just that the commit will not be in its final form so it needs to be modified later, and that's fine - that's basically the core functionality of using git!

If you consider commits and branches as immutable objects you are missing out on the vast majority of git's benefits.

While git stash exists, you are much, much better of never using it and instead just create normal, temporary commits (with a naming convention that makes them visible as such1).


1 And it does not only have to be ==== pre-/post-fix as suggested, I have a ci alias for commit and usually run git ci -am ci to do what git stash sort of would accomplish but without the benefits of creating a real commit. Because "ci" is clearly never a valid commit message on anything final it does not run the risk of being left in on the final branch pushed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.