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:

  1. git stash to save your work
  2. git checkout mybranch
  3. git stash pop to load your last work

Here a some stash commands I find useful:

  • git stash list view everything you have stashed
  • git stash show inspect a stash
  • git 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:

  1. git checkout -b mybranch to create a new branch
  2. git checkout master to checkout back to master branch
  3. git 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!

Umut Esen

Software Engineer specialising in full-stack web application development.

Leave a Reply