git,

Git: restore vs reset vs revert vs rebase

Sep 13, 2022 · 2 mins read · Post a comment

Time to compare yet another somehow confusing Git commands. This time being restore, reset, revert and rebase. Obviously, I won’t be doing a deep dive, and I’ll try to be as plain as possible, so you could get the basic understanding.

Working tree and working directory are used interchangeably.

Prerequisites

  • Git

Solution

git restore

Experimental command at the time of writing. Restore files in the working tree from the index (the staging area where all git add-ed files reside) or another commit.

  • Restore all files in the current directory: git restore .
  • Restore a staged (git add-ed) file: git restore --staged testfile.html
  • Restore both the index and the working tree (same as git checkout):
    git restore --source=HEAD --staged --worktree testfile.html

git reset

A powerful command that resets the working directory to a specific commit. Updates the current branch and the commit history as well.

  • git reset --hard HEAD~1 to undo the last commit.
  • git reset --hard <COMMIT_ID> to undo changes until the specified commit.

As a rule of thumb, use git reset for undoing uncommitted changes.

git revert

Similar to git reset though the only difference is that it creates a new commit for every revert operation.

  • git revert HEAD~1 to undo the last commit.
  • git revert <COMMIT_ID> to undo changes until the specified commit.

As a rule of thumb, use git revert for undoing committed changes.

git rebase

Not so often used or popular command that moves bunch of commits to a new base. Assuming the following example:

     E - F - G ----- feature1
    /
A - B - C - D --------- master

Now, if you git checkout feature1 and run git rebase master the feature1 branch will have a new base tip meaning:

            E - F - G ----- feature1
            /
A - B - C - D --------- master

Conclusion

To find more neat Git commands and hacks, browse the Git category. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.

git