100 Days of DevOps: Day 31
Restoring Stashed Changes in a Git Repository
When working with Git, developers often use the git stash
command to temporarily store unfinished work without committing it. This allows them to switch branches or perform other tasks without losing progress. Later, they can restore these stashed changes when needed.
In this guide, we’ll walk through restoring a specific stash (stash@{1}
) in a repository, committing the changes, and pushing them back to the remote origin.
Navigate to the Repository
First, move into the project directory where the Git repository is located. In our case:
cd /usr/src/kodekloudrepos/news
Check the Available Stashes
To see the list of all saved stashes, run:
git stash list
You’ll see output similar to this:
stash@{0}: WIP on main: Added initial layout
stash@{1}: WIP on main: Updated homepage styles
stash@{2}: WIP on feature-branch: Refactored API calls
Each stash is stored with an identifier like stash@{0}
, stash@{1}
, etc.
Restore the Specific Stash
To restore the changes from stash@{1}
, use:
git stash apply stash@{1}
apply
restores the changes but keeps them in the stash list.
If you want to both apply and remove the stash in one step, you can use:
git stash pop stash@{1}
Verify the Changes
Check what has been restored with:
git status
git diff
This ensures the changes are now back in your working directory.
Stage and Commit the Changes
Once you confirm the changes, stage them:
git add <filename>
Then commit with a descriptive message:
git commit -m "feat: restore changes from stash@{1}"
Push the Changes to the Remote Repository
Finally, push the committed changes to the remote repository:
git push origin main
If your branch name is not
main
, replace it with the correct branch (for example,master
ordevelop
). You can check the current branch with:
git branch --show-current
Key Takeaways
-
git stash
is like a temporary shelf for work in progress. - You can list all stashes with
git stash list
. - Use
git stash apply stash@{n}
to restore without removing, orgit stash pop stash@{n}
to restore and remove. - Always commit and push restored changes to preserve them in the project history.