What is the difference between git diff HEAD and git diff HEAD~1?

The difference between git diff HEAD and git diff HEAD~1 lies in the two versions of the repository that you’re comparing. To understand this difference, we first need to discuss what HEAD and HEAD~1 mean in the context of Git.

  1. HEAD: This is a reference to the ‘current commit’ or ‘last commit’ in the current branch you’re working on. In other words, it points to the most recent commit in your current branch.
  2. HEAD~1: This references the commit before HEAD, or the ‘parent commit’ of the current commit. The ‘~1’ indicates one step back in the commit history. If you were to use HEAD~2, it would mean two commits before HEAD, and so on.

Now, when we use git diff, we’re asking Git to show the differences between two sets of code. The two commands git diff HEAD and git diff HEAD~1 differ in what they’re comparing.

  • git diff HEAD: This command will show the differences between your working directory (the state of your files on disk) and the last commit (HEAD). This is useful to see the changes you’ve made since the last commit that haven’t been staged (added to the index) yet.
  • git diff HEAD~1: This command will show the differences between your working directory and the commit before the last commit (HEAD~1). It will include any changes made in the last commit plus any changes you’ve made since then that have not yet been staged.

To compare just the last two commits, you could use git diff HEAD~1 HEAD, which will show the differences between the last commit and the one before it.

It’s worth noting that git diff by default does not show changes that have been staged (with git add). To include those changes, you would use git diff --cached for staged changes against HEAD, or git diff --cached HEAD~1 for staged changes against HEAD~1. The command git diff --staged is synonymous with git diff --cached.

In summary, git diff HEAD and git diff HEAD~1 are used to compare different sets of code in your Git repository, with the former comparing your working directory with the last commit, and the latter comparing your working directory with the commit before the last commit.