Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to revert a file to a previous version without overwriting current changes?

I'm having a problem trying to revert a file to a previous commit, I know I can use git checkout to revert a single file but the problem is I have changes in that file I'd like to keep so I was wondering how to do some sort of "merge" between a previous commit and the current HEAD for a single file? I tried using git reset sha-of-my-commit path/to/my/file but it puts the previous version in the staging area while keeping the latest version on my working directory not sure how to merge both files after it.

What I did for now was just git diff ..sha-of-my-commit path/to/my/file and just copy/pasted the missing lines but I believe there must be a better way to do this right?

like image 916
Javier Villanueva Avatar asked Feb 03 '12 15:02

Javier Villanueva


1 Answers

Assuming you mean the changes are in your work tree (not committed):

git stash
git checkout previous-commit path/to/file
git stash pop

If you had committed some changes, then you can still do it, with a little more work. Suppose your history looks like this:

- x - A - x - x - x - B - x - x (HEAD)

where you want the version at A, plus the changes from B on. Then do this:

git stash
git checkout B path/to/file
git stash
git checkout A path/to/file
git stash pop
git stash pop

Note that any stash application, since it's a mergey operation, could result in merge conflicts; you should of course resolve those before moving on!

like image 179
Cascabel Avatar answered Nov 15 '22 08:11

Cascabel