1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Getting a Diff

By

Getting a list of changes is useful, but what about getting a diff of what exactly was changed? A diff is a listing of all parts of a file that differ. So, for example, it'll tell you that you removed three lines and added 4 new lines. It's a way of both seeing what was changed and sending those changes to other developers without having to send them the entire file.

Git makes getting a diff easy. There is a git diff command that will compare two sets of files and show you the diff. The first set of files is assumed to be the working tree, but you have to pass the second set of files as an argument to the command. Assuming we want to compare our working tree to the tree last committed (also referred to as the HEAD), we would use the following command.

 $ git diff
 diff --git a/index.html b/index.html
 index 4435dfb..6351e40 100644
 --- a/index.html
 +++ b/index.html
 @@ -4,6 +4,5 @@
    </head>
    <body>
      <h1>Test</h1>
 - <p>This is the body</p>
    </body>
  </html>
 

Reading a diff might be a bit confusing at first. Just remember that any line beginning in a minus was removed in the working set, and any line beginning in a plus was added. Even if you just change a line, it will count that line as removed and the changed version as added.

Though the git diff command has a lot of options, among the most useful is the --unified=n option, which will give you a unified diff with a specified number of context lines. Context lines are the lines before and after any changes you make, and are provided in the diff to give you some idea of where in the code that change was. Occasionally, you'll want more context to be able to see exactly where the changes were, and this option will allow you to specify any number of context lines.

 $ git diff --unified=5
 diff --git a/index.html b/index.html
 index 6351e40..4435dfb 100644
 --- a/index.html
 +++ b/index.html
 @@ -2,7 +2,8 @@
    <head>
      <title>Test</title>
    </head>
    <body>
      <h1>Test</h1>
 + <p>This is the body</p>
    </body>
  </html>
 
  1. About.com
  2. Technology
  3. Ruby
  4. Tutorials
  5. Using the Git Version Control Tool with Ruby
  6. What Did I Change? Getting a Diff

©2014 About.com. All rights reserved.