If you are a developer who is using git, you surely may have encountered this error a lot of times.
Your local changes to the following files would be overwritten by checkout. Please commit your changes or stash them before you switch branches.
On my initial days, if this error occurs, I would discard my local changes (to be on the safe side). I should’ve committed it, right? But what if I don’t want to commit my half-done work? Is there a better way? What is a stash in git? Let’s explore in this blog about the various usage of
git stash command.
You are in the middle of something, and you have got a call to urgently resolve a bug. (Thanks to your boss). So now you need to switch to a different branch and work on the bug fix. But you have changes you have not committed and you are not yet ready to commit this. What will you do?
You have uncommitted files and try to “git pull” and due to conflicts with the remote changes, git may refuse sometimes to overwrite.
Your local changes to the following files would be overwritten by merge. Please commit your changes or stash them before you merge.
This same type of error may also occur during a merge request, while pulling the latest changes from the remote branch.
How will you resolve this scenario?
You had committed to the wrong branch !!! (Seriously, sometimes we make mistakes. Who hasn’t?)
“git stash” could come for your rescue in most of these cases.
According to git-scm documentation, git-stash command is used to
"Stash the changes in a dirty working directory away".
Which means you could throw away your ‘uncommitted changes’ when you don’t want to commit those, in a temporary location (in an intention to take it later). To be precise, your modified ‘tracked’ files and staged changes – will get saved to a ‘stack’ and you can apply these changes later.
We can ‘stash’ the changes by simply executing the following command
To read our indepth tutorial on git stash with more examples, please visit - https://bluecast.tech/blog/git-stash