Git’s diff command is a powerful tool for examining the differences between various commits, branches, or even files in your Git repository. If you want to see the differences in a file before and after it was staged, the following steps will guide you:
1. Checking Differences Before Staging
Before you stage any changes (i.e., before you use git add
), you can use git diff
to see what changes you’ve made since your last commit. This command compares the changes you have made but not yet staged to the latest commit.
If you have a specific file you want to check, you can specify it by appending the filename to the command:
git diff filename
This command will output a list of changes made to the specified file since the last commit that haven’t been staged yet.
2. Checking Differences After Staging
After you’ve staged changes using git add
, the git diff
command, used without any arguments, won’t show any output. This is because git diff
by default shows only unstaged changes. To see the changes you’ve made after staging (i.e., differences between your staged changes and the last commit), you need to use the --staged
(or --cached
in some versions of Git) option with git diff
:
git diff --staged filename
This command will show you the differences between the last commit and the staged changes for the specified file.
Additional Note
You can use git diff
without specifying a filename to see changes across all files:
git diff
to see unstaged changes across all files.git diff --staged
to see staged changes across all files.
Remember, git diff
shows you the differences between your working directory and the index (staging area), and git diff --staged
shows you the differences between your index and the latest commit.
Using git diff
in this manner can be an excellent way to ensure you’re only committing the changes you intend to. It can prevent committing unnecessary changes or debugging code that was not meant to be part of the commit.