I know that Git tracks changes I make to my application, and holds on to them until I commit the changes.
To revert to a previous commit, I used:
$ git reset --hard HEAD
HEAD is now at 820f417 micro
How do I then revert the files on my hard drive back to that previous commit?
My next steps were:
git add .
git commit -m "revert"
But none of the files have changed on my hard drive…
First, it’s always worth noting that
git reset --hardis a potentially dangerous command, since it throws away all your uncommitted changes. For safety, you should always check that the output ofgit statusis clean (that is, empty) before using it.Initially you say the following:
That’s incorrect. Git only records the state of the files when you stage them (with
git add) or when you create a commit. Once you’ve created a commit which has your project files in a particular state, they’re very safe, but until then Git’s not really “tracking changes” to your files. (for example, even if you dogit addto stage a new version of the file, that overwrites the previously staged version of that file in the staging area.)In your question you then go on to ask the following:
If you do
git reset --hard <SOME-COMMIT>then Git will:master) back to point at<SOME-COMMIT>.<SOME-COMMIT>.HEADpoints to your current branch (or current commit), so all thatgit reset --hard HEADwill do is to throw away any uncommitted changes you have.So, suppose the good commit that you want to go back to is
f414f31. (You can find that viagit logor any history browser.) You then have a few different options depending on exactly what you want to do:git reset --hard f414f31. However, this is rewriting the history of your branch, so you should avoid it if you’ve shared this branch with anyone. Also, the commits you did afterf414f31will no longer be in the history of yourmasterbranch.Create a new commit that represents exactly the same state of the project as
f414f31, but just adds that on to the history, so you don’t lose any history. You can do that using the steps suggested in this answer – something like: