Git Stash: Let’s pause the work

OpenInfo
OpenInfo
Published in
2 min readMar 18, 2018

Git stash is something which gives a privilege to developer to save its intermediate changes for later purpose. Lets consider a scenario where you are working on a project in branch new_project_branch and made huge number of changes in source code. Immediately critical issue [Bug] came which needs immediate fix.

Scenario:

  • git status:
It will show you the staged and unstaged changes which are not commited yet.
  • Now, If you try to change the branch then error will come.
git checkout mastererror: Your local changes to the following files would be overwritten by checkout:ansible/ansible.ymlPlease commit your changes or stash them before you switch branches.Aborting
  • Now the options to continue the work is “reset” but it will clear your changes which you don’t want to lose.
git reset --hard
  • Lets start and enjoy your git stash.
  • Git stash saves your current changes internally in Git stash stack So that can be used later.

How it will work and what it will do:

It will save your current changes in git stash stack for later purpose which you can pull anytime using git stash pop command.BUT here is a catch that your newly introduced files will still show in unstage . So be careful in next commit[ Do not blindly use git add . and git commit]. It will stage and commit all the files.

STEPS TO USE:

  • List all the changes and review them before stash.
git status
  • Stash them for later use.
git stash
  • List the stashed changes for verification. Highlighted part will show you code stash stack. [There might be possible to have multiple stash in stash stack which will be identified by the index stash@{0}, stash@{1}, stash@{2}]
git stash liststash@{0}: WIP on my_first_change: 17a8e9b1 First change done to verify git 
  • Change the branch and start working to fix the bug. Refer page for basic git work.
  • Once Changes moved to the master you can resume your work from the place where you left it.
git checkout mastergit pullgit checkout new_project_branch
  • Pull the changes back from stash stack. By default, it will pull the most recent stashed item as it name implies stash stack
git stash pop
  • The git stash pop command always re-apply the most recent snapshot, the one at the top of the stash stack. But, it's also possible to pick and choose which stashed snapshot you want to re-apply with the apply command. For example, if you wanted to re-apply the second set of changes, you would use the following command:
git stash apply stash@{0}

Note: this will not automatically remove the snapshot from the stash stack. Instead, you’ll need to manually delete it with the drop command.

git stash drop stash@{0}

Now you can easily work and avoid conflicts of change in branches.

--

--