To recover a dropped stash in Git, follow these steps using the reflog to locate the lost stash:
1. Find the Dropped Stash in the Reflog
Run the command below to view Git’s reference log, which tracks changes to stashes and branch tips:
git reflog
Look for entries like stash@{n}: WIP on [branch]: [commit-hash] [message]
that correspond to your dropped stash.
Example Output:
abc1234 HEAD@{0}: stash drop: Clearing stash
def5678 HEAD@{1}: stash: WIP on main: 1234567 Initial commit
2. Identify the Stash Commit Hash
Note the commit hash (e.g., def5678
) of the stash entry you want to recover.
3. Recover the Stash
Use the commit hash to restore the stash in one of two ways:
Option 1: Apply the Stash Directly
git stash apply def5678
This applies the changes directly to your working directory without adding them back to the stash list.
Option 2: Re-Create the Stash Entry
git stash branch recovered-stash def5678
This creates a new branch (recovered-stash
) from the stash commit, preserving the changes.
Key Notes
- Act Quickly: Git garbage collection eventually removes unreferenced commits. Recover stashes before they’re pruned.
- Verify Changes: Use
git show def5678
to inspect the stash content before applying. - Alternative for Advanced Users: Use
git fsck --unreachable
to find dangling commits if the stash isn’t in the reflog.
Example Workflow
- Accidentally drop a stash:
git stash drop
- Find the lost stash:
git reflog
# Locate entry: def5678 stash: WIP on main: 1234567 Fix login
- Restore the stash:
git stash apply def5678
Summary
Step | Command | Outcome |
---|---|---|
1. Locate Stash | git reflog | Identify the commit hash of the dropped stash |
2. Apply Stash | git stash apply <hash> | Restores changes to working directory |
3. (Optional) Recreate Stash | git stash branch <name> <hash> | Saves changes to a new branch |
By leveraging Git’s reflog, you can efficiently recover lost stashes before they’re permanently deleted.