How do I discard the changes to a single file and overwrite it with a fresh HEAD copy? I want to do git reset --hard to only a single file.

 

If you want to discard changes to a single file and overwrite it with the version from the latest commit (HEAD) in Git, you can use the git checkout command. Here's how to do it with an example:

Suppose you have a file named "example.txt" with changes that you want to discard and replace with the version from the latest commit (HEAD).

bash
# Discard changes to a single file and overwrite it with the latest commit (HEAD) git checkout HEAD -- path/to/example.txt

In this command:

  • git checkout: This command is used to switch branches or, in this case, to restore files.

  • HEAD: Refers to the latest commit on the current branch.

  • --: Separates the branch (or commit) and the path to the file you want to checkout.

  • path/to/example.txt: Specifies the path to the file you want to reset.

After running this command, the "example.txt" file will be reverted to the state it was in the latest commit (HEAD), discarding any changes you made to it.

Comments