Reverting the Mistaken Change

If you make a modification to a file, and decide that you really didn’t want to change the file at all, and you haven’t yet committed your changes, the hg revert command is the one you’ll need. It looks at the changeset that’s the parent of the working directory, and restores the contents of the file to their state as of that changeset. (That’s a long-winded way of saying that, in the normal case, it undoes your modifications.)

Let’s illustrate how the hg revert command works with yet another small example. We’ll begin by modifying a file that Mercurial is already tracking.

$ cat file
original content
$ echo unwanted change >> file
$ hg diff file
diff -r 68bfacc0125f file
--- a/file	Tue May 05 06:44:36 2009 +0000
+++ b/file	Tue May 05 06:44:36 2009 +0000
@@ -1,1 +1,2 @@
 original content
+unwanted change

If we don’t want that change, we can simply hg revert the file.

$ hg status
M file
$ hg revert file
$ cat file
original content

The hg revert command provides us with an extra degree of safety by saving our modified file with a .orig extension.

$ hg status
? file.orig
$ cat file.orig
original content
unwanted change

Be careful with .orig files

It’s extremely unlikely that you are using Mercurial to manage files with .orig extensions or that you even care about the contents of such files. Just in case, though, it’s useful to remember that hg revert will unconditionally overwrite an existing file with a .orig extension. For instance, if you already have a file ...

Get Mercurial: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.