DEV Community

Wycliffe A. Onyango
Wycliffe A. Onyango

Posted on

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
Enter fullscreen mode Exit fullscreen mode

Check the Available Stashes

To see the list of all saved stashes, run:

git stash list
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

Verify the Changes

Check what has been restored with:

git status
git diff
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Then commit with a descriptive message:

git commit -m "feat: restore changes from stash@{1}"
Enter fullscreen mode Exit fullscreen mode

Push the Changes to the Remote Repository

Finally, push the committed changes to the remote repository:

git push origin main
Enter fullscreen mode Exit fullscreen mode

If your branch name is not main, replace it with the correct branch (for example, master or develop). You can check the current branch with:

git branch --show-current
Enter fullscreen mode Exit fullscreen mode

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, or git stash pop stash@{n} to restore and remove.
  • Always commit and push restored changes to preserve them in the project history.

Top comments (0)