How to Create a Branch from a Git Stash Quickly
To create a new branch from a stash, first create the branch with
git checkout -b <branch-name>, then apply the stash using git stash apply or git stash pop. This lets you work on the stashed changes in a new branch safely.Syntax
Here is the basic syntax to create a branch from a stash:
git checkout -b <branch-name>: Creates and switches to a new branch.git stash apply [stash@{index}]: Applies the stashed changes without removing them from the stash list.git stash pop [stash@{index}]: Applies the stashed changes and removes them from the stash list.
bash
git checkout -b <branch-name>
git stash apply [stash@{index}]
# or
# git stash pop [stash@{index}]Example
This example shows how to create a new branch named feature-from-stash and apply the latest stash to it.
bash
git stash list
# Output: stash@{0}: WIP on main: 123abc Fix bug
git checkout -b feature-from-stash
Switched to a new branch 'feature-from-stash'
git stash apply stash@{0}
# Applies the stashed changes to the new branchOutput
stash@{0}: WIP on main: 123abc Fix bug
Switched to a new branch 'feature-from-stash'
On branch feature-from-stash
Changes applied from stash@{0}
Common Pitfalls
Applying stash without switching branches: Applying a stash on the wrong branch can cause conflicts or unwanted changes.
Using git stash pop without confirming success: If conflicts occur, the stash is not lost but changes are not applied cleanly.
Not specifying stash index: If you have multiple stashes, applying without specifying which one can apply the wrong changes.
bash
git stash pop # If conflicts occur, stash is not lost but changes are not cleanly applied # Correct way: git stash apply stash@{0} # Resolve conflicts if any # Then drop stash manually if successful git stash drop stash@{0}
Quick Reference
| Command | Description |
|---|---|
| git stash list | Show all saved stashes with their indexes |
| git checkout -b | Create and switch to a new branch |
| git stash apply [stash@{index}] | Apply stash changes without removing them |
| git stash pop [stash@{index}] | Apply stash changes and remove from stash list |
| git stash drop [stash@{index}] | Delete a stash after applying it successfully |
Key Takeaways
Always create and switch to a new branch before applying stash to keep work organized.
Use 'git stash apply' to keep stash intact until you confirm changes apply cleanly.
Specify stash index if you have multiple stashes to avoid applying wrong changes.
Avoid using 'git stash pop' blindly as it removes stash even if conflicts occur.
Drop stash manually after successful application to keep stash list clean.