To retrieve an earlier version of a file without losing current uncommitted work, stash the current changes first, check out the old version of just that file, then reapply the stash on top of it.
Key Points: • git stash temporarily removes your current uncommitted changes and stores them separately, restoring the working directory to match HEAD. • git checkout <commit-hash> -- <file-path> pulls just that one file from an earlier commit into your working directory, leaving everything else untouched. • Once you've retrieved and reviewed the earlier version, git stash pop reapplies your stashed changes on top of it. • If the stashed changes overlap with the retrieved content, Git will flag a conflict that needs manual resolution, similar to a merge conflict. • This approach avoids losing either the current in-progress work or the historical version you need to inspect.
Example: A developer wants to see how OrderService.java looked three commits ago while keeping their current unfinished edits; they stash, run git checkout HEAD~3 -- OrderService.java, review the old logic, and then pop the stash back on.
Code Example:
git stash
git checkout HEAD~3 -- OrderService.java
git stash popInterview Tip: A concise interview answer is:
"I'd stash my current changes to get a clean working directory, then check out the earlier version of just that file using git checkout with the commit hash and file path. Once I've retrieved what I need, git stash pop brings my in-progress changes back on top."