githubEdit

Restoring your changes

The simplest case is when you want to restore your uncommitted changes:

$ echo oops >> hello.py
$ git status -sb
# ## main
#  M hello.py
$ git restore hello.py
$ git status -sb
# ## main

If you've already staged the change, you'll need to restore twice:

$ echo oops >> hello.py
$ git add hello.py
$ git status -sb
# ## main
# M  hello.py
$ git restore --staged hello.py
# ## main
#  M hello.py
$ git restore hello.py
$ git status -sb
# ## main
circle-info

Note the position of the Munder the two #s, as these indicate whether the file is staged. You should also see a red Mfor unstaged and a green Mfor staged. As always, if you're confused, run git statuswithout -sbfor more information.

If you've already committed a change, you can revert it:

circle-check

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 mainbranch 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.

triangle-exclamation

Last updated