Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Git & GitHub - Reverting Changes

How to revert changes in Git

Reverting changes in Git allows you to undo modifications, whether they are uncommitted changes in your working directory or committed changes in the repository history. This guide explains how to revert changes in Git using various commands.

Key Points:

  • Reverting uncommitted changes involves using git checkout and git reset.
  • Reverting committed changes can be done with git revert and git reset.
  • Understanding the difference between reverting and resetting is crucial for maintaining a clean project history.

Reverting Uncommitted Changes

To discard changes in your working directory that have not been staged, use the git checkout command. This command reverts the changes in the specified file to the last committed state.


# Discard changes in a specific file
$ git checkout -- filename.txt

# Discard changes in all files
$ git checkout -- .
                

To unstage changes that have been added to the staging area, use the git reset command.


# Unstage a specific file
$ git reset filename.txt

# Unstage all files
$ git reset
                

Reverting Committed Changes

To create a new commit that undoes the changes of a previous commit, use the git revert command. This is useful for maintaining a clean project history.


# Revert a specific commit
$ git revert 
                

Resetting Commits

The git reset command can be used to undo commits and move the branch pointer to a previous state. There are three modes of reset: soft, mixed, and hard.

Soft Reset

A soft reset moves the branch pointer to the specified commit, but leaves the working directory and staging area unchanged.


# Soft reset to a specific commit
$ git reset --soft 
                

Mixed Reset

A mixed reset moves the branch pointer to the specified commit and resets the staging area, but leaves the working directory unchanged.


# Mixed reset to a specific commit
$ git reset --mixed 
                

Hard Reset

A hard reset moves the branch pointer to the specified commit and resets both the staging area and working directory to match that commit. This operation is destructive and should be used with caution.


# Hard reset to a specific commit
$ git reset --hard 
                

Reflog for Recovering Lost Commits

If you accidentally reset or revert commits, you can use the git reflog command to recover lost commits. Reflog shows a history of all actions performed in the repository.


# View reflog history
$ git reflog

# Recover a lost commit using its reflog reference
$ git checkout 
                

Summary

This guide covered how to revert changes in Git, including discarding uncommitted changes, creating new commits that undo previous commits, and using reset to move the branch pointer. Understanding these commands is essential for maintaining a clean and accurate project history.