How to use git to revert changes to individual files or foldersvidual

This is something I need to do often and often forget how to do it.

tl;dr: git checkout main <filename>

Disclaimer:

Like anything else this is nuanced and there are other ways to accomplish this as well as other arguments to revert to a point in time instead of just the tip of main.

Revert a commit

If you want to a revert a whole commit you can do git revert <hash>.

Revert a file or folder

But what if you want to revert one file or one folder to what is in your main branch?

You can do git checkout main <filename>.

An example repository where you have this structure:

repo-root
├── main.swift
├── Service
│   ├── Service.swift
│   └── README.md
└── start-docker.sh

You could do git checkout main main.swift to undo main.swift to where it was on main.

Or you could do git checkout main Service to undo the whole directory to where it was on main.

Why would I want to do this?

The situation where I found this useful was that I had a long running branch and I wanted to merge part of the code into main. The problem was there were a handful of files that I did not want to merge to main.

I could have reverted the commits where they were made, but this branch had a lot of commits and I wasn’t sure exactly when these changes were made.

I also could have manually changed them back to what they were in main, but this was a better solution for my use case.

Maybe you’ll find it useful as well.