Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to undo file deletions from a historical commit?

Tags:

git

github

In one repo, I have a commit (about 3 behind the HEAD) that has a large number of file deletions that were accidentally staged and included in the commit. Depending on the file type, they appear like either of the following when executing git log --stat:

path/to/some/file                     | Bin 22522 -> 0 bytes
path/to/another/kind/of/file          | 1 -

I would like to reverse these deletions and not have any of them appear in my commit. (Note: I'm not trying to hide the deletions, so if there is a method that reverses them, that is fine, too. I just don't want my PR to merge in these file deletions.)

If there's something I should do to update the remote after reversing the file deletions, that would be helpful as well.

like image 826
zahabba Avatar asked Apr 07 '26 06:04

zahabba


1 Answers

This has nothing to do with moving HEAD, but selectively cancelling (in Git linguo, "reverting") some files from a commit.

In your case, the @~3 commit includes deletions you don't want, but also other files (you might not want to revert to).

git revert --no-commit @~3 # Revert, don't commit it yet
git reset                  # Unstage everything

# add only the files you need (ie the one created, not the ones modified)
git add $(git ls-files -o --exclude-standard)

Here you want, after reverting the all commit @~3, to select only the untracked files (that is, the files created again by git revert, since those creation cancel what was deleted in @~3).
See "Git add only all new files, not modified files".

like image 111
VonC Avatar answered Apr 09 '26 03:04

VonC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!