I find myself working on the wrong branch locally far too many times – enough to write a post about it.
If you have been working on the wrong branch, your commit could be blocked by git:
Please, commit your changes or stash them before you can switch branches.
Code language: Bash (bash)
Git stash is extremely useful when you want to temporarily save undone or messy work, while you want to do something on another branch.
You can use:
git stash
to save your workgit checkout mybranch
git stash pop
to load your last work
Here a some stash commands I find useful:
git stash list
view everything you have stashedgit stash show
inspect a stashgit stash apply
restore a stash on top of your current branch
If you have somehow already committed to the wrong branch, you will have to:
git checkout -b mybranch
to create a new branchgit checkout master
to checkout back to master branchgit reset --hard origin/master
to reset master with remote and remove local commits
Hopefully this quick post helped move your local changes to the correct branch.
Do you know another way to switch git branch with local changes? Let me know in the comments below!