How to discard changes in a file in Git

Discarding unstaged changes in specific files allows you to revert unwanted modifications without affecting other files in your working directory. As the creator of CoreUI with over 25 years of development experience, I frequently discard experimental changes or accidental modifications when working on complex features. The most precise approach uses git checkout with the file path to restore the file to its last committed state. This method provides surgical control over change management while preserving other work in progress.

Use git checkout -- filename to discard unstaged changes and restore the file to its last committed state.

git checkout -- src/components/Button.js

This command discards all unstaged changes in the specified file, reverting it to exactly how it appeared in the last commit. The -- separator ensures Git treats everything after it as a file path, preventing conflicts with branch names. This operation is irreversible for unstaged changes, so use it carefully when you’re certain you want to lose the current modifications.

Best Practice Note:

This is the selective change discarding method we use in CoreUI development for precise file management during feature development. Always verify which changes you’re discarding with git diff filename before running this command to avoid losing important work.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author