Restoring your changes
The simplest case is when you want to restore your uncommitted changes:
If you've already staged the change, you'll need to restore twice:
If you've already committed a change, you can revert it:
For any of these commands, you can replace the commit hash with an expression like HEAD~1
, which means one commit before the current state (the head of the tree). You can change this number to go further.
If you want to restore a file to how it was at a certain point in time, that's also possible:
Note that this just changes the file. You're still on the hook to stage and commit the change, as usual. If you want to revert the entire repository to how it was at a certain commit, you can do that too:
So far, all of these commands keep the history intact, and simply add new commits to undo older ones. By adding --hard
, you can actually take the repository back to an earlier commit, discarding all commits since then.
It should go without saying a command like this is very dangerous, and you can very quickly lose a lot of work if not done correctly. There are times when this is necessary, however, like when you've accidentally committed to the main
branch and need to restore it back to the last commit on GitHub. In cases like this, you can first create a temporary branch and then perform this command on main
, leaving your commits intact on the new branch.
Pushing is forever. If you've pushed a commit, no amount of resetting locally can undo that, and you can't change history on remote repositories. Never reset a commit with --hard
that you've already pushed to a remote branch.
Last updated
Was this helpful?