Usage of git stash

2 min read | by Jordi Prats

While working on a change it can happen that someone else have updated the remote repository with completely unrelated changes. Instead of having to perform a merge commit we can download the changes to apply our changes on top of that commit.

First thing we need to do is save all the date in the stash:

$ git stash
Saved working directory and index state WIP on CHG-6750: Initial Commit

All the changes are going to be reverted so, now, we can fetch all the changes on the remote repository without a merge commit:

$ git pull origin master
From ssh://
 * branch            master     -> FETCH_HEAD
Updating saddsda..0610670
Fast-forward |  4 ----   |  2 +-  | 12 +++++++++++-
 3 files changed, 12 insertions(+), 6 deletions(-)
 delete mode 100644

At this point the tip of our local repository is in sync with the remote one thus we can now apply the changes we saved on the stash.

We can using git stash apply to apply the changes we have on the stash keeping them in the stash (we might want to apply them on several branches):

$ git stash apply

Or we can use git stash pop if we want to apply the changes and remove them from the stash:

$ git stash pop

Now we can just commit all the changes as usual to push it to the remote repository without a merge commit:

$ git add --all
$ git commit -va
[CHG-6750 2123382] CHG-6750 Fixed helm_repository deprecation
 4 files changed, 15 insertions(+), 1 deletion(-)

Posted on 06/01/2021