GIT Practical Reference

Undoing Changes in Git

Discarding All Uncommitted Changes

To discard all uncommitted changes in your working directory, you can use the git reset command with the --hard option:

git reset --hard

This command resets your working directory to the last committed state, removing all changes you made since the last commit.

Discarding Specific Uncommitted Changes

If you want to discard specific changes in a file while keeping others, you can use the git checkout command followed by the file name you want to discard changes from:

git checkout <file_name>

Undoing the Last Commit (without losing changes)

To undo the last commit while keeping the changes staged in your working directory, you can use the --soft option with git reset:

git reset --soft HEAD~1

This command moves the HEAD pointer to the previous commit, effectively "undoing" the last commit while preserving the changes.

Undoing the Last Commit (losing changes)

To undo the last commit completely, including the changes in your working directory, you can use the --hard option with git reset:

git reset --hard HEAD~1

This command not only moves the HEAD pointer but also discards all changes made in the last commit.

Reverting Commits

Another way to undo commits is by creating a new commit that undoes the changes introduced by a previous commit. Unlike reset, revert command doesn't move the pointer to the previous commit, instead it creates a new commit undoing changes made by the specified previous commit.

To do this, you can use the git revert command:

git revert <commit_hash>

Replace <commit_hash> with the hash of the commit you want to undo.