Have you ever tried to run git pull origin main
and been met with this dreaded message?
This error often happens when you're working on a file locally while the same file was also updated in the remote repository. Git doesn't know how to automatically merge those changes unless you clean things up first.
In this article, I’ll show you how to fix this issue without losing your work, using Git’s powerful stash
command.
🔍 The Problem: Merge Conflict with Local Changes
Here’s the situation:
-
You made local changes to your project files.
-
Someone else also made changes and pushed them to the remote repository.
-
You try to pull the latest version with
git pull origin main
, but Git blocks you.
Why? Because if Git merges automatically, it could overwrite your local edits. To avoid that, it forces you to decide what to do first.
🧰 The Solution: Git Stash to the Rescue
Git stash
is like a clipboard that temporarily holds your changes so you can safely pull and then reapply them.
🪄 Step-by-Step Fix
✅ 1. Stash Your Current Changes
This will temporarily save (stash) all your local uncommitted changes.
Sample output:
✅ 2. Pull the Latest Changes from Remote
Now that your changes are out of the way, Git can update your working directory without conflict.
Sample output:
✅ 3. Reapply Your Stashed Changes
This will bring back your local changes and apply them on top of the updated project. Git will attempt to merge them automatically. If changes overlap, it may show merge conflicts for you to resolve manually.
Sample output:
🎯 Optional: Committing or Cleaning Up
After this, your Git status might look like:
Now choose one of the following:
➕ Option A: Commit Your Local Changes
If you’re happy with the result:
Done. You’re clean again!
🧹 Option B: Discard Local Changes
If you don’t want those changes anymore:
To discard untracked files as well (be careful):
Use git clean -fdn
to preview what will be deleted.
📝 Summary
Step | Command | Purpose |
---|---|---|
1️⃣ | git stash | Save your local changes |
2️⃣ | git pull origin main | Pull latest updates from remote |
3️⃣ | git stash pop | Reapply your changes after pulling |
✅ | git add . && git commit | (Optional) Commit changes |
❌ | git restore . | (Optional) Discard changes |
To avoid these headaches in the future, create a separate branch for your feature development:
This way you can freely work and merge changes back when you're ready.
🦆 Final Thoughts
If you're managing projects where multiple files change often example in master.blade.php
or blog post templates getting comfortable with Git stash and pull is essential.
You’re now ready to handle Git merge conflicts like a pro—without losing any work. 💪
Leave a Reply