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 blindly 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? Will all of my work be instantly in the correct branch and I can commit and push as normal?
I am nodding off and unsure of how not to blow up my Git project.
This post answers my question, I think, but is it up to date? Also, from that post:
To also stash currently untracked (newly added) files, add the argument
-u
What is the difference between uncommitted and untracked/newly added files? Aren't uncommitted files more or less "newly added"?
That is exactly one of the use-cases for stashing. If the modified files would not be different between the two branches you would be able to switch the branches without stashing. But Git sees that your branch switch would overwrite some of your changes and it refuses to do so if you don't force it to.
So yes, you stash, switch the branch, then pop the stash. You will then probably get merge conflicts that you can resolve and if you did this correctly, you have all your work back and can test and commit to the correct branch.
If you created new files locally and the same files were added in the branch you switch to, you also have the problem that the switch would overwrite your local files. For this it is helpful to also stash the untracked files.
The difference between untracked and uncommitted files in that terminology is, that untracked files are not known to Git at all yet and uncommitted files are files Git already tracks but you made changes to them. Untracked files are also uncommitted of course.