git/stash

Stash Changes

Temporarily save your uncommitted changes without committing them, allowing you to work on something else and restore them later

git
stash
changes
save
temporary

Command

git stash

Explanation

The `git stash` command temporarily shelves (or "stashes") changes you have made to your working directory so that you can work on something else, and then come back and reapply them later. This is useful when you need to quickly switch branches or pull in updates but aren’t ready to commit your current work. When you run `git stash`, Git takes the changes in both your staged and unstaged areas, saves them in a special stack, and then reverts your working directory to the last committed state. You can then use commands like `git stash apply` or `git stash pop` to reapply the stashed changes. Stashes are stored locally and are specific to your repository. You can list, show, drop, or apply specific stashes as needed.

Common Use Cases

  • You need to switch branches but don’t want to commit incomplete work
  • Temporarily saving changes while pulling updates from a remote branch
  • Trying out experimental code without losing current progress
  • Cleaning working directory for testing or debugging

Best Practices

  • Always use descriptive messages with each stash (`git stash save "message"`) to identify them easily later
  • List stashes regularly with `git stash list` to manage them
  • Apply stashes selectively when switching between multiple tasks
  • Drop stashes you no longer need using `git stash drop` to keep your stash list clean

Common Mistakes to Avoid

  • Forgetting to apply the stash later and losing track of it
  • Assuming stash is shared with remote repositories (it is local only)
  • Using stash without a message, making it hard to identify later
  • Overwriting important stashes by repeatedly using git stash without saving custom messages

Troubleshooting

Problem: Changes not appearing after applying stash

Solution: Ensure you’re on the same branch or working context as when you created the stash. Try `git stash apply stash@{n}` for a specific stash.

Problem: Conflicts when applying stash

Solution: Resolve conflicts manually after running `git stash apply`. You can view what was stashed using `git stash show -p stash@{n}`.

Problem: Stashed files missing from stash

Solution: By default, untracked files are not stashed. Use `git stash -u` to include them.

Examples

Stash current changes (both staged and unstaged)

git stash

Apply the latest stash and remove it from the stash list

git stash pop

Show a list of all stashed changes

git stash list

Stash changes with a custom message

git stash save "WIP: fixing bug"

Include untracked files in the stash

git stash -u