How to Reset Changes in a Single File in Git

Updated onbyAlan Morel
How to Reset Changes in a Single File in Git

Sometimes you make a mistake and need to reset some changes in your local repository. More specifically, sometimes you only need to replace a single file.

In this post, we'll learn how to reset the state of a single file in your local repository to any commit or branch you have.

Resetting a Single File

To reset a single file, simple use the git checkout command.

Let's say our file was called README.md and we want to reset it to the latest version of the same branch:

BASH
[git](https://sabe.io/tutorials/learn-git) checkout -- README.md

This will reset any changes you've made to the file since the last commit.

Specify a Commit

Maybe you don't want the latest but instead a specific commit. To specify a commit, add it to the git checkout command:

BASH
git checkout [commit hash here] -- README.md

Specify a Branch

You can also specify a branch to reset to, rather than a commit hash on the same branch:

BASH
git checkout [branch name here] -- README.md

For example:

BASH
git checkout origin/master -- README.md

Reset a Stage File

When you've staged a file already, like running this command:

BASH
git add README.md

You will first need to unstage the file. To do so, use the git reset command:

BASH
git reset HEAD README.md

Once that's done, you can run your usual git checkout command to reset the file to the latest version of the same branch.

BASH
git checkout -- README.md

Conclusion

In this post, we've seen how you can reset a single file in your local repository to any commit or branch you have.

You can also reset a file to a specific commit or branch, depending on your needs. You can even reset a file you've already staged.

Hopefully, this post has helpful information for you. Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.