In this article I’ll show you a simple example of how to revert changes to files in a Git repository.
This is the second of a three part article serie about Git. Read part one here.
If you followed the steps in the first Git article then you should have a working installation of Git.
Let’s start with setting up the things needed for this example so fire up you terminal and create a new directory:
1
|
|
Create a new repository and add a new file to it:
1 2 3 4 |
|
Open list.txt
and add some text to it. Then add the change and commit it:
1 2 |
|
Log and Diff
Now that you have some commits the fun can begin. To see all the commits for a list.txt
use this command:
1
|
|
1 2 3 4 5 |
|
As you can see this lists the author, time, the commit message and a SHA-1 hash calculated based on the contents of the files.
Add another line to list.txt
and commit the change:
1 2 |
|
To show all the changes through history made to our file, use the following command:
1
|
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
The plus sign indicates an addition and a minus sign indicates that something is deleted.
Revert back to previous version
Now let’s get to the point of this article, how to fetch an older version of the file. Let’s go back to the point right before we added c# to the list. To do so we need to know the commit’s SHA-1 hash where we made that change. Run the handy git log -p list.txt
command to find it.
My output says that c# was added in the commit with the SHA-1 hash of: 9c70282186975e49dc58080fcc9bd9fac28ef683
. To get back to that point but only affect the one file we need to change use the following command:
1
|
|
The output of git status
now shows that the file is both staged for a commit and modified. Why? It’s because git reset
moves the file from one point in the commit index and then modifies it back to the latest version again. This is complex stuff and out of scope for this article but if you really want to understand how git reset
works I suggest you read this brilliant post by Scott Chacon.
There are a few steps left to complete this. Since we actually only moved the file within the repository we need to checkout that change with this command:
1
|
|
This fetches the file from the repository in its current state and updates the working directory.
Now all you need to do is to add the change and commit it.
1 2 |
|
As you can see, by using git you don’t need to be afraid of removing code, experiment or try new features. Your code is always backed up and older versions is right there at your fingertips.