Git stash

TL;DR

  1. Use git stash to stash changes.
  2. Update from remote using git pull.
  3. Apply stash changes to latest changes using git stash pop.
  4. If there's a merge conflict, manually resolve using some text editor like Nvim. Changes from upstream and stash are demarcated with angle brackets.
  5. After resolving, add, commit, and push!
  6. Clean up stash using git stash clear.

If there are no merge conflicts skip step 4 and 6 because the stash gets cleared automatically.

See also my additional notes.

Details

More often than I would like, I get into the situation where I have uncommitted changes but I need to pull new changes from remote. This is where git stash becomes useful. Instead of committing incomplete code or discarding changes, you can stash them and bring them back when needed. I've done this several times but I forget what happens, so I'm writing this blog post as a reference point for myself.

I'll use an old GitHub repository that I created when I was first trying out Git. To create the scenario where I need to pull new changes from remote, I will clone the repo at commit 6daeb4cf5d6774c7dc29d4e74c4c595bd5a9452f.

Next I'll make some changes to README.md on github.com and commit to main.

Locally, I'll make some changes to README.md and I will try to pull.

From github.com:davetang/try_git
   6daeb4c..16eb9d5  main       -> origin/main
Updating 6daeb4c..16eb9d5
error: Your local changes to the following files would be overwritten by merge:
        README.md
Please commit your changes or stash them before you merge.
Aborting

As advised, I'll run git stash.

git stash
Saved working directory and index state WIP on main: 6daeb4c Create README.md
git stash list
stash@{0}: WIP on main: 6daeb4c Create README.md

Now I can pull.

git pull
Updating 6daeb4c..16eb9d5
Fast-forward
 README.md | 4 ++++
 1 file changed, 4 insertions(+)

Now to add my changes from my stash.

git stash pop
Auto-merging README.md
CONFLICT (content): Merge conflict in README.md
On branch main
Your branch is up to date with 'origin/main'.

Unmerged paths:
  (use "git restore --staged <file>..." to unstage)
  (use "git add <file>..." to mark resolution)
        both modified:   README.md

no changes added to commit (use "git add" and/or "git commit -a")
The stash entry is kept in case you need it again.

Take a look inside README.md.

cat README.md
# README

Trying out Git.

<<<<<<< Updated upstream
## Testing git stash

Adding some lines using github.com.
=======
## Local changes

A line added locally.
>>>>>>> Stashed changes

Remove the comments, then add, commit, and push!

Finally, to clean up run git stash clear.

git stash clear
git stash list
# no output



Creative Commons License
This work is licensed under a Creative Commons
Attribution 4.0 International License
.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.