Here is my strategy to solve the problem.
Problem Statement
We need to make changes in more than 10 files. We tried PULL (git pull origin master)
, but Git shouted:
error: Your local changes to the following files would be overwritten by merge: Please, commit your changes or stash them before you can merge.
We tried to execute commit
and then pull
, but they didn't work either.
Solution
We were in the dirty stage actually, because the files were in the "Staging Area" a.k.a "Index Area" and some were in the "Head Area" a.k.a "local Git directory". And we wanted to pull the changes from the server.
Check this link for information about different stages of Git in a clear manner: GIT Stages
We followed the following steps
git stash
(this made our working directory clean. Your changes are stored on the stack by Git).git pull origin master
(Pull the changes from the server)git stash apply
(Applied all the changes from stack)git commit -m 'message'
(Committed the changes)git push origin master
(Pushed the changes to the server)git stash drop
(Drop the stack)Let's understand when and why you need stashing
If you are in the dirty state, means you are making changes in your files and then you are compelled, due to any reason, to pull or switch to another branch for some very urgent work, so at this point you can't pull or switch until you commit your change. The stash
command is here as a helping hand.
From the book ProGIT, 2nd Edition:
Often, when you’ve been working on part of your project, things are in a messy state and you want to switch branches for a bit to work on something else. The problem is, you don’t want to do a commit of half-done work just so you can get back to this point later. The answer to this issue is the git stash command. Stashing takes the dirty state of your working directory – that is, your modified tracked files and staged changes – and saves it on a stack of unfinished changes that you can reapply at any time.