Post

Git Stash

Stashing a Specific File Before Pulling from Git

Introduction

Sometimes, you need to pull the latest changes from main, but you have local modifications to a specific file that you don’t want to lose. Instead of stashing all changes, you can stash only a single file, pull the latest updates, and then reapply your stashed changes safely.

Step 1: Stash Changes for a Specific File

To stash changes for a single file while keeping a descriptive message, run:

1
git stash push -m "Stashing myfile changes" -- path/to/myfile

This command stores only the changes in path/to/myfile without affecting other modified files.

Step 2: Pull the Latest Changes

Once the file is safely stashed, pull the latest updates from main:

1
git pull origin main

Step 3: Reapply Stashed Changes

After pulling, apply your stashed changes back:

1
git stash pop

Alternative: Handling Stash Conflicts

If git stash pop results in conflicts, use git stash apply instead:

1
git stash apply

Once everything looks good and the changes are merged properly, remove the stash manually:

1
git stash drop

Helpful Commands for Managing Stashes

List Current Stashes

To see all stashed changes, run:

1
git stash list

Example output:

1
2
stash@{0}: On main: Stashing myfile changes
stash@{1}: On main: WIP before pull

This allows you to reference specific stashes if needed.

Apply a Specific Stash

If you have multiple stashes and want to apply a specific one instead of the latest, use:

1
git stash apply stash@{1}

Summary

By following these steps, you can safely update your local branch without losing changes to a specific file. This approach is especially useful when working in teams to avoid unnecessary merge conflicts.

This post is licensed under CC BY 4.0 by the author.