Git Stash

Assume you are on a Branch and there is a need to switch to another branch. Why would you need to move to another branch? Here are some reasons:

  1. There is a Development Env bug that you need to quickly look at.

  2. A Production hotfix should go right away.

  3. Or a urgent code review where you need to pull & switch to another branch

  4. Or just someone asked you to check something on a different branch

You can do this in a couple of ways

  1. Commit your changes. (May take more time)

  2. Git Stash.

Git Stash

Git stash is a useful Git command that temporarily stashes changes you've made to your working directory so you can work on something else. Later you can come back and re-apply your stashed changes.

Here are some common commands and usages for git stash

  1. Stashing Changes

    • git stash: Stash the changes in your working directory. This command temporarily stores all modified tracked files.

    • git stash save [message]: Same as git stash, but allows you to add a descriptive message to the stash for easy identification.

  2. Listing All Stashes

    • git stash list: Lists all stashed changes. Stashes are stored in a stack and can be listed to see all.
  3. Viewing Stash Contents

    • git stash show: Shows the changes recorded previously in the stash as a diff between the stashed changes & the original state.

    • git stash show stash@{n}: Show the changes in the specified stash.

  4. Applying Stashed Changes

    • git stash apply: Re-apply the changes stored in the latest stash.

    • git stash apply stash@{n}: Apply the changes from the specified stash.

  5. Removing a Stash

    • git stash drop stash@{n}: Remove a single stash entry from the list of stashes.

    • git stash clear: Remove all the stashed entries.

Here is how to make it work (For Please play with a temporary repository):

You are on some branch and you have some changes done but not committed and now you need to switch to another branch:

  1. git status // To see what all you are working on.

  2. git stash // Save your current changes into the stash.

  3. git checkout ... // to another branch and complete your work.

  4. git stash list // To see what stashed I've.

  5. git stash apply // To apply the latest stashed code.

Did you find this article valuable?

Support Sandeep Gokhale's Blog by becoming a sponsor. Any amount is appreciated!