Reverting changes in Git

As I wrote earlier, I started using Git pretty intensively lately and I had to find out the hard way that some commands behave quite differently from what I was used to with Subversion.

One such command, which I use pretty often, is revert. In Subversion, this command will undo all your local edits, essentially reverting the state of your working directory to match the repository. Not in Git.

With Git, issuing the revert command, means reverting a previous commit instead. This can actually be pretty useful when you want to roll back changes you have already committed (there is no easy way to do this in Subversion), but sometimes you just want to trash all uncommitted changes with no questions asked (and no trace in the commit log).

The command that does this is called reset *. The reset command, unsurprisingly, resets the state of your working directory to match the repository (sounds familiar?). It takes a commit, such as HEAD for the current revision, as a parameter and an optional tag to specify how the reset should take place. If you want to really replace any locally modified files by the originals from the repository, use the –hard flag. This makes the command look like this:

git reset --hard HEAD

which behaves pretty similar to svn revert.

What this does not do, is clean up any files in your working directory that were never added to the repository in the first place. This sometimes happens to me when I mistype a Ruby on Rails generate command, which creates a lot of files containing the same mistake. Luckily, git also has a command to fix this: clean. The command

git clean -df

will remove all files and directories unknown to git. Watch out (using git status) that this does not accidentally delete too much, such as sqlite3 databases that you forgot to add to .gitignore.

Git’s revert and reset behaviour may not always be the same on a per command basis, the functionality is there. You just have to use the right commands :)

*: Actually, the reset command is a lot more powerful, but you should check out the documentation for that.

6 Responses to “Reverting changes in Git”

  1. Pingback: Steffen

  2. Pingback: Joao

  3. Pingback: Sanjeev

  4. Pingback: Sanjeev

  5. Pingback: autowebnew.com

  6. Pingback: www.rebelmouse.com