Key Points
- To stash current changes, run git stash. This command saves your uncommitted work and returns your working directory to the last commit.
- To label or add a note to a stash, use git stash push -m “message”.
- To see everything you’ve stashed, run git stash list. This will show you each stash’s identifier and message.
- To bring stashed changes back, use git stash apply to keep the stash as a fallback, or git stash pop to remove it once reapplied.
- To remove stashes you no longer need, use git stash drop for one stash or git stash clear to delete all of them.
- To include new, untracked files in a stash, add the –include-untracked flag or its shorthand, -u.
Git stash is a Git command that temporarily saves uncommitted changes in your working directory, allowing you to switch branches or tasks without committing unfinished work.
This guide will delve into git stash, starting with its basic concept, utility, and use cases. We will then cover its basics, such as how to retrieve and manage stashes, and explore advanced techniques. Best practices and their importance in software development will conclude our guide, ensuring a comprehensive understanding of git stash.
Git and the significance of git stash
Before diving into the specifics of git stash, it’s crucial to understand Git itself. Git, in a nutshell, is a distributed version control system widely used in software development to track changes to source code. Its distributed nature allows multiple developers to work simultaneously on the same codebase without interfering with each other’s work.
Key features that make Git indispensable to developers include:
- Branching and merging: Git’s branching model allows developers to work in isolated environments called “branches,” and merge their changes back to the source code seamlessly.
- Speed and efficiency: Git is designed for performance. Its operations are fast, making it suitable for projects of any size.
- Data integrity: Git ensures the integrity of source code by maintaining a complete history and full version tracking capabilities.
Understanding these aspects of Git sets the stage for a deeper exploration into the git stash command, a tool that, while less frequently discussed than others like git commit or git merge, can nevertheless be an invaluable part of a developer’s toolkit.
What is git stash?
The git stash command is a powerful feature in Git. It is essentially a mechanism for saving the current state of your working directory and index without committing. It’s like a clipboard for uncommitted changes, offering a snapshot that can be reapplied later. This feature is integral in version control as it helps manage code changes more flexibly and efficiently. It temporarily shelves, or “stashes,” changes that you have made to the working directory, allowing you to work on something else and then come back to them later.
Git stash is most helpful when you’re:
1. Saving work in progress
Scenario: When a developer needs to switch to another branch to focus on a critical issue, but is in the middle of implementing a new bug fix.
Use case: Git stash saves current changes without committing them, enabling developers to switch to another branch or make changes before returning to the original branch and retrieving their stashed changes.
2. Cleaning the working directory
Scenario: A developer has made uncommitted changes in their working directory that they cannot lose, but they want to start working on a new feature from scratch.
Use case: Git stash temporarily removes uncommitted changes. It cleans a working directory, enabling developers to create a new feature from scratch and then reapply their previous changes.
3. Testing different approaches
Scenario: When a developer is working on a solution and wants to try a new approach, without losing their current work.
Use case: Git stash lets developers stash their current changes so they can try different approaches. This gives them a clean slate to experiment with. They can revert to their stashed changes if their new approach doesn’t work.
4. Resolving merge conflicts
Scenario: When a developer wants to temporarily stash some changes to deal with other urgent issues while coming up with a resolution for a complex merge conflict.
Use case: Git stash temporarily saves changes, enabling developers to focus on other issues and then return to resolving merge conflicts.
5. Partial stashing
Scenario: When a developer wants to choose only some of the multiple changes that they want to stash from the changes in their working directory.
Use case: Git stash allows for stashing specific files or parts of them, giving developers more control over what gets stashed.
6. Working with multiple features
Scenario: When a developer needs to switch between multiple features they’re working on simultaneously.
Use case: Git stash allows developers to save their progress on the feature they are currently working on so they can switch to another feature without losing the changes they made. Developers can stash their work on a feature branch, switch to another branch, and then reapply the stashed changes once they initially switch back to the feature they’re working on.
7. Code reviews
Scenario: When a developer needs to leave uncommitted changes in their working directory to review a colleague’s code.
Use case: Git stash allows developers to stash their changes, review their colleagues’ code, and then reapply their stashed changes once they return to their working directory from looking at their colleague’s code.
8. Backing up uncommitted work
Scenario: When a developer wants to back up their uncommitted changes to another branch or a remote repository.
Use case: Git stash allows stashing changes, creating a new branch from the stash, pushing that branch to a remote repository, and backing up a developer’s uncommitted work.
9. Collaborative work
Scenario: When a developer needs to pull the latest repository without losing their local changes, but is working on a shared repository.
Use case: Git stash allows developers to stash their changes and then pull the latest changes or updates from the remote repository. They can then reapply their stashed changes afterward.
10. Automating workflow
Scenario: When a developer uses scripts or hooks that require a clean working directory.
Use case: Git stash allows developers to stash their changes before running scripts or hooks. They can then reapply them afterward to ensure a clean working directory for automation processes.
These are just the most common use cases of Git stash, demonstrating its flexibility in providing solutions and streamlining development workflows.
Common git stash limitations
Like most git commands, git stash has its limitations, such as:
- It’s not a substitute for commits.
- Stashes are local, not shared across repositories.
- Untracked and ignored files are not stashed by default.
How to use git stash
Stashing changes in Git is straightforward. Simply use git stash in your working directory. This command will stash any modified and staged changes, leaving you with a clean working directory.
Stash your changes
- Make changes in your working directory.
- Run git stash to stash the changes.
- The working directory returns to the state of the most recent commit.
Stash changes with a message
To annotate your stashes with a message, use git stash push -m “message”. This helps in organizing and identifying stashes, especially when working with multiple stashes.
View your stashes
Use git stash list. This command displays a list of all stashes, each with an identifier and the message (if provided).
Include untracked files
By default, git stash only stashes tracked files or files that have been added to the index. You can use git stash –include-untracked or git stash -u to stash untracked files.
Stash specific files
If you only want to stash specific files or directories, use git stash push -m “message” –path/to/file1 path/to/file2. This command is particularly useful when you want to make separate changes in different files or directories and manage them independently.
Stash selected changes
git stash -p lets you select specific changes to stash, providing you with more control over what gets stashed.
How to apply git stashes
Apply the latest stash
git stash apply re-applies the most recent stash and keeps it saved in your stash list.
Apply and remove the latest stash
git stash pop restores your stashed changes and permanently deletes them from your list.
Apply a specific stash
If you want to apply specific stashes from multiple stored stashes, list them with git stash list and apply the desired stash using its identifier: git stash apply stash@{n}.
Troubleshooting common git stash issues
Resolving stash application conflicts
- Problem: Conflicts when applying a stash due to overlapping changes.
- Solution: Manually resolve conflicts in the affected files, then run git add and commit them.
Handling stashes in detached HEAD state
- Problem: Applying stashes after working in a detached HEAD state.
- Solution: Check out to the desired branch, then apply the stash using git stash apply or git stash pop.
Avoiding stash duplication
- Problem: Duplicate stashes after applying without dropping.
- Solution: After applying a stash, use git stash drop to remove it if it’s no longer needed.
How to manage and delete git stashes
Delete a specific stash
git stash drop stash@{n} lets you delete specific stashes.
Delete all stashes
git stash clear removes all stashes you’ve made.
Recover a dropped stash
If you accidentally dropped a stash, use git reflog to find its commit hash, then reapply it with git stash apply <commit-hash>.
Best strategies for stash management
- Use descriptive stash messages: Add a clear note to each stash you create so you can quickly identify what they contain when reviewing your stash list.
- Stash changes before switching branches: To keep your working directory clean, stash your changes first before transferring to a different branch.
- Regularly review and clear unnecessary stashes: Apply or drop stashes once you no longer need them to keep your stash list clean and organized.
- Use commits for long-term changes: Relying on stashes as permanent storage can make tracking and managing changes difficult over time. Use commits instead to preserve important work and make it easier to review or restore changes.
Advanced git stash commands
Here are a few advanced git stash commands that cater to both common and more specialized use cases:
Preserve staged changes
Normally, when you apply a stash, the changes that were staged when the stash was created are no longer staged. Using git stash apply –index reapplies the stash and also stages the changes that were staged at the time of stashing.
Create a branch from a stash
If you have a stash that should be on a separate branch, the git stash branch new_branch_name stash@{n} command creates a new branch from the commit where the stash was created, applies the recent changes to it, and then drops the stash.
It’s an excellent way to manage stashed changes that have evolved into a more significant feature or bug fix.
Common git stash limitations
- It’s not a substitute for commits.
- Stashes are local, not shared across repositories.
- Untracked and ignored files are not stashed by default.
Advanced git stash techniques
On stashing specific files or changes
To stash specific files, use git stash push [file1] [file2]. This targets only the specified files or changes, providing more control over what is stashed by enhancing the granularity of stash control.
Handling conflicts when applying stashed changes
When applying stashes, conflicts might arise. Handle them as you would with a merge conflict: edit the files to resolve conflicts, then add and commit them.
Git stash aids in branch switching
- Stashing changes in the current branch.
- Switching to the target branch.
- Applying the stash to the new branch.
Git stash best practices
Like many other development processes, git stash also includes strategies that help developers utilize its powerful functionalities. Here are some git stash best practices:
Use stash sparingly: In other words, do not overuse git stash. Instead of stashing, use dedicated branches for long-term work-in-progress. Remember to use the command moderately, especially when it’s only needed to work on another task, because it will affect the changes that must be made in committing.
Use clear, descriptive stash messages: Developers can add a descriptive message describing the changes they are stashing. With this in mind, they should always be clear with their stash messages and avoid unnecessary ones. Making the stash meaningful and informative helps developers remember what exactly is in their stash when they return to it later. Clear messages also make it easier to identify and apply the correct stash later, facilitating retrieval.
Leverage branches: Always ensure that a new branch is created before stashing changes. This allows you to switch to different tasks or branches without affecting your current changes. You can then revert to the branch and apply the stash when you decide to work on the modifications again.
Stash untracked files: One of the best practices developers should always follow is to use commands that stash untracked files. This reduces the risk of data loss or of important changes being made.
Manage multiple stashes: Commands enable developers to manage multiple stashes effectively. These include git stash list for viewing all existing stashes, git stash apply stash@{<n>} (where <n> represents the stash’s index) for applying a specific stash, and git stash drop stash@{<n>} (where <n> represents the stash’s index) to remove a stash if you no longer need it.
Consider stash pop carefully: Much like the first best practice, the stash pop command (git stash pop) should be used with good discernment. While this command offers a quick way to apply and remove a stash, the operation can cause merging of conflicts if the stashed changes conflict with the current working tree. Alternatively, you can utilize the git stash apply command to apply the stash without deleting it. This enables you to resolve any conflicts manually before removing the stash with git stash drop.
Make the changes as quickly as possible: Storing should only be used as a temporary solution. Once you have finished making a set of changes, you should commit them to the repository to preserve a record of the changes.
Other useful Git stash strategies
How to maintain a clean Git history
- Commit for permanence: Prefer commits over stashes for permanent changes.
- git commit -m “Commit message”
- Stash housekeeping: Regularly clean up stashes.
- git stash list followed by git stash drop stash@{n}
- Temporary haven: Use stashes for temporary, not long-term changes.
Common git stash pitfalls to avoid
- Avoid excessive stashing: Over-relying on stash for important changes.
- Remember to unstash: Forgetting to apply or drop stashes.
- git stash apply or git stash pop
- Stash awareness: Losing track of what each stash contains.
- git stash list to review stashes
- Clarify with comments: Confusing stashes due to insufficient stash comments.
- git stash save “Descriptive message”
When incorporating git stash in team-based projects
- Communicate your stashes: Communicate any stashed changes that may affect
- Workflow enhancement: Use stashes to improve personal workflow.
- Keep stashes local: Avoid pushing stashes to shared repositories unless a new branch needs to be created from a stash in order to commit local changes to the repository as gracefully as possible.
Git stash, git commit, git reset, and git stage: What are the differences?
Since we have already discussed git stash, let’s see how it differs from other Git commands, such as commit, reset, and stage.
Git commit
Git commit is a command that enables developers to save changes to the source code and store them in the local repository. They do this to keep a snapshot of a project at a specific point in time so they have a reference that reflects the project’s current state, including staged changes, as of when they were working on it. To put it in context, here’s a table of their distinctions below:
Git reset
Git reset is a complementary command to git stash that lets you manage changes to a Git repository. With these two commands combined, developers can retrieve backed-up and previously deleted files and send them back to the repository. But git stash and Git commit also have differences, which you can see in the table below:
Git stage
The Git stage is used to prepare changes for commit. The process involves adding the changes to the staging area or “index,” allowing developers to review them before committing.
The table below shows the key differences between git stash, git commit, git reset, and git stage:
| Feature | Git Stash | Git Commit | Git Reset | Git Stage |
| Purpose | Temporarily saves uncommitted changes | Permanently saves changes to the project history | Resets the current HEAD to a specific state | Prepares changes for commit |
| Reversibility | Can be applied or dropped later | Requires git revert or git reset to undo | Can be undone with git reflog, but can be destructive | Staging area |
| Data Loss | Can switch branches without committing | Does not affect branching | Can lose uncommitted changes (depending on options) | Requires git commit to commit |
| Branching | Multiple stashes can be created | Commits are linear | Can change the branch or create a new one | Changes can be unstaged with git reset HEAD <file> |
Want to switch branches without losing progress? Watch how to use Git stash.
The practice of stashing cultivates good development habits
Regularly stashing uncommitted changes encourages developers to maintain a clean and organized codebase, which in turn reduces the likelihood of conflicts and errors. It’s a practice that, when used judiciously, can significantly enhance the overall efficiency and effectiveness of version control management.
This feature is not just a mere command in the vast array of Git functionalities; it’s a critical tool for efficient and flexible coding workflows. Its ability to temporarily sideline work in progress allows developers to maintain a clean working directory, which is essential in complex software development environments where focus and organization are key.
The versatility of git stash lies in its simplicity and the broad range of scenarios it caters to – from quick context switches to experimenting with new features without disrupting the main codebase. This functionality is especially beneficial in collaborative settings where multiple developers are contributing to the same project.
Stashes help in ensuring that each developer’s work remains intact and unaffected by the changes of others, thereby fostering a more seamless and productive collaboration.
Whether you’re a novice programmer just starting out with Git or an experienced developer, the ability to adeptly use git stash is an invaluable skill in your software development toolkit. It offers a strategic way to handle code changes, aligns well with effective development practices, and ultimately contributes to more streamlined and agile project management.

