My Profile Photo

Dipen Ved


Hello there, I am Dipen, currently exploring my developer instincts at Microsoft. My interests broadly lie in the areas of Algorithms, Natural Language Processing, Design Patterns and Blockchain. Between my sleeps, when I am not coding, I generally like to travel, read and play badminton.


About Git Stash

Many a times I observe developers relying only on basic git commands -

  • git push
  • git pull
  • git fetch
  • git checkout
  • git add
  • git commit

and may be few more. There would be cases where you started developing the code in an incorrect branch, and only while committing your changes you realize that the branch which is selected is incorrect.
The wrong way to fix this, is to manually copy the same changes after selecting the correct branch and deleting the previous branch or rebasing the commit.
One bad way to fix this, is to commit in the existing branch and then cherry-picking the commit later with git cherry-pick <commit-hash>.
This is where git stash comes into the picture.

Whether one needs to save their changes for time being and work fresh from the previous commit, or one is trying to switch branches with current changes to a new/existing branch, git stash is the simplest solution.

As the English dictionary defines stash - to store or hide something. git stash does the same for code changes.

Once we have the changes, not committed, we can create a stash and store it for future use or reuse.
git stash push -m "sample_stash"
This would now create a stash with name “sample_stash” and store it.

Now to get the list of all stashes stored in the repository currently,
git stash list will show the list of all the stashes.

To apply a stash and remove it from the stash stack, we can use
git stash pop stash@{i}

And to just apply and not remove from the stack, we have
git stash apply stash@{i} where i is the index of stashed change.

If you feel after stashing, that the stash is important enough, you can always turn a stash into a branch.
git stash branch <branchname> [<stash>]
This command creates a new branch with name as "branchname" from the commit stash was created and applies the <stash>. If stash is not provided, it applies the latest one. After successful creation, the stash is dropped from the list.

The other interesting way to save your changes is by using patches. You are store your changes in a patch and then re-apply it later.
git diff > sample.patch
git apply sample.patch
It would be a clever idea to add .patch extension in .gitignore file.

Hoping you got to know something new today. Until next time.

comments powered by Disqus