1

Let's say I remove a line from a file and I commit and push that change:

commit 4dd87

$ vim myfile.txt //remove line from file
$ git add myfile.txt
$ git commit -m "line added"
$ git push origin master

Now, I make another change and I push it:

commit 84674

$ vim myfile.txt //make another change, whatever
$ git add myfile.txt
$ git commit -m "another change"
$ git push origin master

Now, I want to recover the line that I removed in first commit. I would do it with the next steps:

1) Go to commit previous to remove the line (previous to 4dd87) with git reset --hard 4dd87 2) Apply changes of second commit with git cherry-pick 84674 3) Force push with git push origin master --force

But there are many drawbacks using this approach when there are more people pushing to the repo.

So, is there a better way?

Héctor
  • 24,444
  • 35
  • 132
  • 243
  • 3
    Use `git revert`, which creates a new commit that reverts the changes made in the original one. – Thomas May 24 '18 at 15:14
  • @Thomas Great, that's what I was looking for. Thank you very much! – Héctor May 24 '18 at 15:21
  • note that, although it is an improvement over OPs solution, it is not ideal to make another commit if you just want to restore the file. Also `git revert` can not single out a file, if you have multiple files committed. Lastly it does not really help if there are have been multiple commits and you want to see how your file was before them. – Frido Emans May 24 '18 at 21:03

2 Answers2

3

Use git revert, which creates a new commit that reverts the changes made in the original one.

Thomas
  • 174,939
  • 50
  • 355
  • 478
1

The easiest is this: check out file from previous commit:

git checkout 4dd87 myfile.txt

now you have your file back the way it was in 4dd87, and ready to be committed, or you can modify it further.

Frido Emans
  • 5,120
  • 2
  • 27
  • 42