Reputation: 275
Are git stash
and git stash pop
a good solution for this problem?
I was working on branch B, but something happened accidentally and unbeknownst to me, put me back into an older branch, branch A, where I kept working on various tasks.
Git wants me to commit my new work to branch A, before I can switch over to branch B, but I can't (shouldn't) do that.
Is it safe (meaning will I not lose all my work, but be able to put it over into its correct branch) to, while on branch A (the wrong branch), do git stash
, then switch to branch B (correct branch) and do git stash pop
? Will I encounter any disasters by doing that?
I am unsure of how not to blow up my Git project!
Upvotes: 2
Views: 224
Reputation: 521249
Your current situation sounds like a good reason to use git stash
. You said the following:
Git wants me to commit my new work to branch A, before I can switch over to branch B, but I can't (shouldn't) do that.
Believe it or not, git stash
actually makes two commits (sometimes even three) to preserve your working directory and stage before resetting them, allowing you to switch branches.
However, you could actually make a temporary commit yourself. Then switch to branch B, do you work there, and when you return to branch A, you can continue. When it comes time to commit your work, you can actually amend the temporary commit via:
git commit --amend
This will rewrite the HEAD commit on branch A, and there will effectively be no trace of the temporary unfinished work you were doing there.
Upvotes: 0
Reputation: 1276
I think git stash
is perfect for your purpose and, according to me, this post confirms my opinion.
Maybe you could have some conflict to be solved.
I hope this will help you.
Upvotes: 0
Reputation: 106430
This seems like an appropriate move. Using git stash
will preserve your working index at the time you discovered the discrepancy, and will allow you to then safely move your code to the branch you need it on.
Just as an FYI, git stash pop
will move things out of the stash and into the index, but also delete what was in the stash. My preference in situations where I'm not 100% sure is to use git stash apply
instead, so I can always retrieve the previous working index I stashed until I feel safe enough to delete it.
Upvotes: 3