Git & GitHub ยท Chapter 12 of 42

git diff

The `git diff` command shows the exact line-by-line differences between your working directory, staging area, and commits. It's essential for reviewing changes before committing.

By default, `git diff` shows unstaged changes. Adding `--staged` (or `--cached`) shows what's staged and ready to be committed instead.

Syntax
git diff
git diff --staged
git diff commit1 commit2

Comparing working directory changes

Running `git diff` with no arguments shows differences between your working directory and the last commit for files that are not yet staged.

Comparing staged changes and commits

`git diff --staged` shows staged changes compared to the last commit. `git diff commit1 commit2` compares two specific commits.

Example 1 (bash)
git diff app.js
Output
-const x = 1;
+const x = 2;

Shows that the line 'const x = 1;' was changed to 'const x = 2;' in app.js.

Example 2 (bash)
git add app.js
git diff --staged
Output
-const x = 1;
+const x = 2;

After staging, --staged shows the same change is now ready to be committed.

Key points

  • git diff shows line-by-line differences between file versions.
  • By default it compares working directory to the last commit.
  • --staged shows differences already added to the staging area.
  • You can diff between any two commits by hash or branch name.
๐Ÿ’ก Note: Lines starting with - are removed and lines starting with + are added in the diff output.

๐Ÿ“ Quick Quiz

1. What does git diff show by default?

2. Which flag shows staged changes in a diff?

3. In diff output, what does a line starting with + mean?