How to read a git diff

When I learned how to read a git diff/patch, I felt like my understanding of the internal mechanics of git improved. Here’s a little tid bit I’m going to use as an example to illustrate some of the different components:

 1. diff --git a/bootstrap.sh b/bootstrap.sh
2. index e98ae1c..9073c4d 100644
3. --- a/bootstrap.sh
4. +++ b/bootstrap.sh
5. @@ -1,6 +1,6 @@
6. #!/usr/bin/env bash
7.
8. -apt-get update
9. +sudo apt-get update
10.
11. wget -qO- https://raw.githubusercontent.com/...
12.
13. @@ -9,3 +9,4 @@ echo "source /home/vagrant/.nvm/...
14. source /home/vagrant/.profile
15.
16. nvm install node
17. +nvm alias default node

This is from a git diff associated with a commit on my lets-learn-vagrant repository on GitHub.

Lines 1 through 4 have some information about the diff, including file names of the original files and modified/new files.

On line 5, @@ indicates the start of a new hunk, which lasts from lines 5 to 12.

  • Ln 5 -1,6 means: "the original file, starting on line 1, had 6 lines before this diff was applied."
  • Ln 5 +1,6 means: "the modified/new file, starting on line 1, has 6 lines after this diff is applied."
  • Ln 6 #1/usr/bin/env bash is part of the original file and remains unchanged because the beginning of the line starts with a space.
  • Ln 7 is also whitespace that remains unchanged.
  • Ln 8 apt-get update is removed as shown by its leading -.
  • Ln 9 sudo apt-get update is added, per the + at the beginning of the line.

Because this hunk has 1 line removal and 1 line addition, the total number of lines before and after the patch is applied remains unchanged, as per line 5’s @@ -1,6 +1,6 @@.

Now let’s take a look at the second hunk in this git diff/patch on lines 13 to 17.

  • Ln 13 -9,3 +9,4 indicates that the following information shows the original file, starting on line 9, had 3 lines of code, and the modified/new file, starting on line 9, has 4 lines of code.
  • Lns 14–16 all lead with a whitespace (aka there are no changes)
  • Ln 17 nvm alias default node has a +, so it's a new addition!

A random observation I made: Each hunk is buffered at the beginning and end (for context) by 3 unchanged lines for git diff and 7 unchanged lines for git add --edit for my current git configuration.

Like what you read? Give Robin Kim a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.