LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
Git & GitHub

Git Stash and Conflict Resolution – Handle Complex Scenarios

Your current changes are incomplete. You cannot commit them yet. Git Stash temporarily saves uncommitted changes so you can switch tasks safely. We will also learn how to handle conflicts when two changes affect the same lines of code.

Git Stash and Conflict Resolution – Handle Complex Scenarios

Imagine you are working on a payment feature. You have modified three files, but your team suddenly asks you to fix a production bug on another branch. Your current changes are not ready to commit. What should you do?

You could create a temporary commit, copy the changes somewhere else, or use Git's stash feature. Git stash gives you a clean working directory by temporarily saving your uncommitted changes. Later, you can restore those changes and continue your work.

In this article, you will learn:
  • How Git stash saves and restores unfinished work.
  • How to manage multiple stashes and restore selected files.
  • How to apply stashed changes on another branch.
  • How merge conflicts and stash conflicts happen.
  • How to resolve conflicts safely in real-world team workflows.

1. What Problem Does Git Stash Solve?

Git tracks changes in your working directory. Sometimes you need to switch branches, pull recent changes, or investigate an urgent issue while your current work is incomplete.

For example, you are implementing a new loan approval API. You have modified the controller, service, and validation files. Before committing, your team asks you to switch to the production-fix branch.

Git may prevent the branch switch if your uncommitted changes would be overwritten. Stash helps you temporarily save those changes without creating a normal commit.

Important: Git stash is a temporary local storage mechanism. It is not a replacement for regular commits, backups, or remote branches. Stashes are stored in your local repository and are not automatically shared with your team.

2. Understanding Git Stash Internals

A stash entry is a Git object that records your working-tree changes and, when applicable, your index (staging area) changes. Git also records the base commit from which the work started.

When you run git stash push, Git saves the selected changes and normally restores the tracked working tree and index to a clean state relative to the current commit.

Working directory Unfinished changes Stash entry Saved locally Clean working tree Switch branches safely Apply or pop Restore saved changes Continue coding Review and commit

The stash workflow: save unfinished changes, work elsewhere, and restore them when ready.

3. Create Your First Stash

Let's use a simple employee management project. You have modified two tracked files and want to switch branches without committing the unfinished feature.

Example 1: Check your current changes

git status

Illustrative output

On branch feature/employee-search
Changes not staged for commit:
  modified:   src/EmployeeService.cs
  modified:   src/EmployeeController.cs

Save these changes with a meaningful message:

Example 2: Stash tracked modifications

git stash push -m "WIP: employee search implementation"

Illustrative output

Saved working directory and index state
On feature/employee-search: WIP: employee search implementation

Now check the working directory again:

git status
On branch feature/employee-search
nothing to commit, working tree clean

Your tracked changes have been saved in a stash entry. You can now switch branches or perform another task.

4. Stash Commands You Should Know

Common Git stash commands and their purpose
Command Purpose
git stash push -m "message" Save changes with a descriptive message.
git stash list List available stash entries.
git stash show Show a summary of the latest stash.
git stash show -p Show the patch for the latest stash.
git stash apply Apply the latest stash and keep it in the stash list.
git stash pop Apply the latest stash and remove it if application succeeds.
git stash drop Remove a selected stash entry.
git stash clear Remove all entries from the stash list.
git stash branch name Create a branch from the stash's original base and apply it.

5. Manage Multiple Stash Entries

In real projects, you may have multiple unfinished tasks. For example, you might temporarily save a payment validation change, then save a separate logging change.

Example 3: Create multiple stashes

git stash push -m "WIP: payment validation"
git stash push -m "WIP: audit logging"
git stash list

Illustrative output

stash@{0}: On feature/payment: WIP: audit logging
stash@{1}: On feature/payment: WIP: payment validation

The newest stash is normally at index stash@{0}. Older entries have higher indexes. These indexes can change when entries are added or removed, so inspect the list before selecting one.

Example 4: Inspect and apply a specific stash

git stash show -p stash@{1}
git stash apply stash@{1}
Apply versus pop: Use apply when you want to keep the stash as a backup while checking the restored changes. Use pop when you are comfortable removing the stash after a successful application.

6. Stash Untracked and Staged Changes

By default, git stash push saves changes to tracked files. New untracked files are not included unless you request them.

Include untracked files

Example 5: Save tracked and untracked changes

git stash push -u -m "WIP: include new test files"

The -u option is the short form of --include-untracked. It includes untracked files but not ignored files.

Include ignored files too

git stash push -a -m "WIP: include ignored files"

The -a option includes ignored files as well as untracked and tracked changes. Use it carefully because build output, local configuration, and generated files may be large or sensitive.

Stash only selected files

git stash push -m "WIP: controller only" -- src/EmployeeController.cs

This lets you stash selected paths while leaving other changes in your working directory. Review git status afterwards to understand exactly what remains.

Keep staged changes in the index

git stash push --keep-index -m "Save unstaged work"

--keep-index leaves the staged changes in the index and stashes the unstaged changes. This is useful when you want to commit only the already-staged work.

Do not assume every stash option behaves identically. The options control which changes are included and what remains in your working tree. Always inspect the result with git status and git stash show -p.

7. Restore Stashed Work on Another Branch

One useful scenario is moving unfinished work to a separate branch. This is especially helpful when the original branch has changed significantly or you want to isolate a task.

Example 6: Create a branch from a stash

git stash list
git stash branch feature/employee-search-recovery stash@{0}

Git creates the new branch starting from the commit on which that stash was originally created, then attempts to apply the saved changes. If the operation succeeds, Git normally drops that stash entry.

Why is this useful? Applying an old stash directly onto a branch with a very different history may cause conflicts. Creating a branch from the stash's original base can make recovery easier.

8. What Is a Git Merge Conflict?

A merge conflict happens when Git cannot automatically combine changes. A common example is when two developers modify the same lines in the same file in different ways.

Suppose one developer changes the payment timeout to 30 seconds while another changes the same line to 60 seconds. Git cannot decide which business rule is correct.

Base commit timeout = 15 Feature branch timeout = 30 Main branch timeout = 60 Merge conflict Developer decides

Git detects incompatible edits but cannot determine the intended business rule.

9. Understand Conflict Markers

When Git reports a content conflict, it marks the conflicting section inside the file. Consider this example from PaymentConfiguration.cs:

Example 7: Conflict markers inside a file

<<<<<<< HEAD
var paymentTimeout = 60;
=======
var paymentTimeout = 30;
>>>>>>> feature/payment-timeout

These markers mean:

  • <<<<<<< HEAD begins the current branch's version.
  • ======= separates the two versions.
  • >>>>>>> feature/payment-timeout ends the incoming branch's version.

The marker labels depend on the operation and repository state. During a merge, HEAD generally represents the current branch, while the other side represents the branch being merged.

Never simply delete the conflict markers and keep the first version. Understand both changes and confirm the correct business behaviour before resolving the conflict.

10. Resolve a Merge Conflict Step by Step

Let's resolve the payment timeout conflict. Assume the team has confirmed that the correct production timeout should be 45 seconds.

Step 1: Identify the conflicted files.
git status

Git lists files under unmerged paths. Open each file and locate its conflict markers.

Step 2: Understand both changes.

Check the current branch's change, the incoming branch's change, and the requirement from the team. Do not make a decision based only on which version is newer.

Step 3: Edit the file and remove conflict markers.

Keep the agreed implementation:

var paymentTimeout = 45;
Step 4: Mark the file as resolved.
git add PaymentConfiguration.cs

Adding the file tells Git that you have resolved its conflict. It does not automatically verify that your code is correct.

Step 5: Complete the merge.
git status
git diff --check
git diff --cached

Review the staged result, run relevant tests, and then complete the merge:

git merge --continue

If your Git version or workflow does not require this command, completing the merge with the normal commit workflow may be appropriate. Follow the instructions shown by Git.

11. Resolve a Stash Conflict

A stash conflict is different from a normal branch merge conflict, but the resolution process is similar.

For example, you stashed a change to EmployeeService.cs. Meanwhile, another developer changed the same lines on the branch where you now want to restore your work.

Example 8: Apply a stash

git stash apply stash@{0}

If Git cannot apply the patch cleanly, it reports conflicts and leaves the affected files in an unmerged state. Inspect the repository:

git status

Open the conflicted files, understand both versions, edit the final content, and stage the resolved files:

git add src/EmployeeService.cs
git diff --cached
git status

Run the relevant tests before committing your resolved changes. Since this was a stash application rather than a merge operation, you do not normally run git merge --continue.

Important difference: If git stash pop encounters conflicts, Git normally keeps the stash entry because it could not complete the pop successfully. Resolve the working-tree conflict, verify your changes, and then decide whether to drop the retained stash. Do not drop it before confirming that your work is safe.

12. Understand Git's Three-Way Conflict Stages

During a content conflict, Git's index can hold three versions of a file:

Unmerged index stages
Stage Meaning
Stage 1 Common ancestor version, when available.
Stage 2 Ours — the current side of the operation.
Stage 3 Theirs — the incoming side of the operation.

You can inspect these versions with:

git ls-files -u
git show :1:PaymentConfiguration.cs
git show :2:PaymentConfiguration.cs
git show :3:PaymentConfiguration.cs

Not every conflict has all three stages. For example, an add/add conflict or a delete/modify conflict may have a different set of available entries.

13. Advanced Conflict Resolution Scenarios

Scenario A: Keep the current branch's version

During a merge, you can choose the current side for a particular conflicted file:

git checkout --ours -- PaymentConfiguration.cs
git add PaymentConfiguration.cs

Scenario B: Keep the incoming branch's version

git checkout --theirs -- PaymentConfiguration.cs
git add PaymentConfiguration.cs
Be careful with ours and theirs. Their meaning depends on the operation. During a normal merge, ours is the current branch and theirs is the branch being merged. During a rebase, the perspective can be surprising because commits are replayed onto another base. Inspect the actual file versions before choosing.

Scenario C: Abort a merge

If you decide that the merge should not continue, you can return to the pre-merge state when Git can safely do so:

git merge --abort

Scenario D: Reuse previous conflict resolutions

Git can remember how you resolved a conflict and reuse that resolution when the same conflict appears again. This feature is called rerere (reuse recorded resolution).

git config --global rerere.enabled true
git rerere status
git rerere diff

Review any automatically reused resolution before completing the operation. Rerere saves time; it does not replace code review or testing.

14. Common Mistakes and Best Practices

Common mistakes and recommended practices
Mistake Better approach
Using stash without a message. Use descriptive messages to identify the task.
Assuming untracked files are included. Use -u when untracked files must be saved.
Running pop without checking the target branch. Verify the branch and working-tree state first.
Dropping a stash immediately after a conflict. Verify restored files and tests before dropping it.
Keeping one side without understanding the requirement. Review both versions and confirm the intended behaviour.
Resolving conflicts without running tests. Run unit tests and relevant integration tests.
Using stash as permanent storage. Commit meaningful work and push it when appropriate.

15. Real-World Team Workflow

Consider a team developing a lending platform. You are working on a loan eligibility feature, but a critical production issue requires immediate attention.

  1. Save your unfinished tracked changes with a descriptive stash message.
  2. Switch to the production-fix branch and resolve the urgent issue.
  3. Commit and push the production fix through the team's normal review process.
  4. Return to your feature branch and inspect the latest remote changes.
  5. Restore your stash using apply so the original entry remains available during verification.
  6. Resolve any conflicts, run tests, and review the final diff.
  7. Commit your completed feature and remove the stash only when it is no longer needed.

Example 9: A practical workflow

# Save unfinished feature work
git stash push -u -m "WIP: loan eligibility validation"

# Switch to the production fix
git switch hotfix/payment-timeout

# Complete and commit the hotfix
git add .
git commit -m "Fix payment timeout validation"

# Return to the feature branch
git switch feature/loan-eligibility

# Update local branch from remote
git pull --ff-only

# Restore the unfinished work
git stash apply stash@{0}

# Inspect and test the restored changes
git status
git diff

If the pull or stash application produces conflicts, stop and resolve them deliberately before continuing. The exact workflow may vary depending on your team's branching and review policies.

16. Interview Questions and Answers

Q1. What is Git stash?

Git stash temporarily saves selected uncommitted changes and restores the working tree to a clean state. It helps developers switch tasks without creating a temporary commit.

Q2. What is the difference between git stash apply and git stash pop?

apply restores a stash but keeps the entry. pop restores it and removes the entry when the application succeeds. If a pop conflicts, the stash is normally retained.

Q3. How do you stash untracked files?

Use git stash push -u or git stash push --include-untracked. Use -a when ignored files must also be included.

Q4. What causes a Git merge conflict?

A conflict occurs when Git cannot automatically combine changes, such as incompatible edits to the same lines, or certain add/delete and rename situations. A developer must inspect and resolve the result.

Q5. What is the difference between ours and theirs?

In a merge, ours usually refers to the current branch and theirs to the incoming branch. During a rebase, the perspective can differ. Always inspect the operation and file contents before selecting a version.

Q6. How do you inspect a stash before applying it?

Use git stash list to identify entries and git stash show -p stash@{n} to inspect the selected patch.

Q7. What happens if git stash pop results in a conflict?

Git reports the conflict and normally keeps the stash entry because the pop was not completed. Resolve and test the working-tree changes before deciding whether to remove the retained entry.

Q8. What is git rerere?

Rerere means reuse recorded resolution. Git can record a conflict resolution and reuse it when the same conflict occurs again. The reused result should still be reviewed and tested.

17. Hands-On Practice

Try these exercises in a local test repository:

  1. Create a branch and modify two tracked files. Save the changes using a descriptive stash message.
  2. Create an untracked file and stash it using -u. Verify that it is restored correctly.
  3. Create two stash entries and apply the older one by its stash reference.
  4. Create two branches that modify the same line. Merge them and resolve the conflict manually.
  5. Apply an old stash after changing the same file on the target branch. Inspect and resolve any conflict.
  6. Use git stash branch to recover work on a new branch.
Practice goal: You should be able to save unfinished work, recover a selected stash, understand conflict markers, inspect Git's unmerged index, and safely complete or abort a merge.

18. Conclusion

Git stash is a practical tool for managing unfinished work when priorities change. It helps developers switch tasks without creating unnecessary commits. Conflict resolution is equally important because Git cannot always determine how two different changes should be combined.

In professional development, the safest approach is to inspect changes, understand both sides of a conflict, preserve important work, resolve deliberately, and run the relevant tests before committing.

Remember: stash helps you manage unfinished work, while commits preserve meaningful project history. Use both appropriately.

Official Documentation

Upgradix by Shrash Studio

Learn Technology. Build Your Future.

Quality Technology Education. Completely Free.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.