Skip to main content

Git Stash

Git stash is an important and useful feature in Git that allows you to save changes that you don't want to commit immediately. It takes your modified tracked files, stages changes, and saves them on a stack of unfinished changes that you can reapply at any time.

Why Use Git Stash?

There could be scenarios where you are working on a feature and suddenly need to switch your work to a different branch without committing the current changes. This is where git stash becomes handy. It takes away all your changes, stores them somewhere temporarily, and allows you to re-apply them later.

How to use Git Stash?

To use the git stash command, first, modify a file in your repository. Don't stage or commit the changes. Then, type the command git stash in your terminal.

git stash

This command saves your changes away and reverts your working directory back to the state of the last commit.

How to Apply Stashed Changes?

To reapply previously stashed changes, you can use the git stash apply command. This command takes the changes stored in the stash and re-applies them to your working directory.

git stash apply

You can also use git stash pop to apply the stashed changes and remove them from the stash stack.

git stash pop

How to List Stashed Changes?

You might have multiple stashed changes. To view all your stashed changes, use the git stash list command.

git stash list

This command will list all the stashed changes with their corresponding stash id, which you can use to apply or drop a specific stash.

How to Apply/Drop a Specific Stash?

To apply or drop a specific stash, you can use its corresponding stash id, which you get from the git stash list command.

To apply a specific stash:

git stash apply stash@{2}

To drop a specific stash:

git stash drop stash@{2}

In the above commands, replace '2' with your desired stash id.

Conclusion

Git stash is a powerful tool that can help you save changes that you don't want to commit immediately. It's especially useful when you need to switch branches but don't want to lose your current work. Practice using the git stash command to become more proficient in managing your Git repositories.