How would you use git diff to compare the current state of a file with a specific commit?

git diff is a powerful command in Git’s arsenal, which allows developers to review the changes between different commits, branches, or even the current working state of the project. In this case, if we want to compare the current state of a file with a specific commit, we’ll need to know the commit hash of that commit.

Let’s suppose we have a file named example_file.txt and a commit hash like abc123.

We would use the following command:

git diff abc123 -- example_file.txt

This command will output the differences between the current state of example_file.txt and how it was in the commit with hash abc123.

Let’s break it down:

  • git diff: This is the command that shows the differences between two points in your project.
  • abc123: This is the commit hash. It’s a unique identifier for each commit. You can find it by running git log and looking at the ‘commit’ field.
  • --: This is a common convention used in command line applications to signify the end of command options, after which only positional parameters are accepted.
  • example_file.txt: This is the file you’re interested in. You can replace this with any file in your project.

The output will be a unified diff format that shows added and removed lines. Lines that are added are prefixed with a +, and lines that are removed are prefixed with a -.

Please note, if you haven’t committed your current changes, and you want to compare your local, uncommitted changes with a specific commit, you can just use git diff abc123 without specifying the file name.

Also, remember to replace abc123 with your actual commit hash and example_file.txt with your actual filename.