GIT Notes: Undoing Changes

GIT Succinctly – free eBook from Synfusion

    Chapter 4 Undoing Changes

Undoing changes in git could mean,

  • Undo changes in working directory
  • Undo changes in staging area
  • Undo a entire commit

Changes can be made by deleting a commit or by using a new commit to undo changes introduced by the first commit.
The recent commit is the ‘HEAD’.
Make the working directory and the stage, match the files in the most recent commit. (This will actually change files in your working directory!!!)

$ git reset
$ git reset --hard HEAD (not sure about difference between these?)

To get rid of (meaning to delete) untracked files,

$ git clean

‘-f’ option forces deletion of these files,

$ git clean -f

(What is the difference between an ‘option’ e.g ‘-f’ and a ‘flag’ e.g. –hard? Or are these terms used interchangeable? Perhaps options are single character and reppended with a single hyphen and flag are mutiple charactered and preppended with double hyphens?)
A ‘reset –hard’ makes all files in the working directory and staging sync with the lastest commit.
Make a single file in the working directory match the version in the most recent commit, (bypasses staging)

$ git checkout HEAD

You can replace HEAD with a commit ID, branch or tag to make the file match the version in that commit. This command is like
NB Do Not Try this with ‘git reset’
To unstage a file,

$ git reset HEAD

This will not change the working directory.
To reset every file in the working directory and staging,

$ git reset --hard HEAD

This results in an unstaged modification in ‘git status’.
Undoing commits:
‘reset’ will remove it from project history
‘revert’ which generates a new commit that gets rid of changes introduced in the original.
To move the HEAD reference back one commit,

$ git reset HEAD ~1

This removes the most recent commit. Or you can go back two commits with ‘~2’, this also removes the two most recent commits. Not good to do this on public projects with other collaborators.
Reverting adds a new commit that undoes the problem commit

$ git revert

This takes the changes in the specified commit, figures out how to undo them, and creates a new commit with the resulting changeset. This t=is the way to undo a commit with a public repository.
Replace a previous commit instead of creating a new one,

$ git commit --amend

This rewrites history!

Posted in git