Showing differences of staged files with git

Something I don’t like about git, primarily because it doesn’t fit into my
personal development workflow, is how git diff only applies to files that have not been staged to commit.

Sure, it makes sense if you are the type to stage files locally on a regular
basis without pushing to remote. That’s not me though, the very nature of
committing and pushing to remote gives me an instant backup of my code in the event of some sort of doomsday scenario happening to my system.

Regardless of my preferred way to work, git diff works as it does. If your
files have been staged for commit, running git diff won’t show any changes.

To get around this, you can include the --cached argument to show the
differences of files you’ve already staged:

# Differences of all staged files
git diff --cached

# Differences of a specific staged file
git diff --cached ./path/to/staged/file
Zsh

The --cached argument can be a bit tricky to remember, since we’re talking
about “staged” files and not “cached” files. Fortunately, you can use the
--staged argument, which is a synonym for --cached.

Sadly, you can’t use the --cached argument as a drop-in replacement for git diff without any arguments. The reason is, when you use the --cached argument, you’re only getting the differences of the staged files, excluding any changes that may have been made since the files were staged.

You could probably get your hands dirty by throwing some shell script at the problem, trying to determine if you have staged files or not and then running the appropriate (or both) git diff commands.

Maybe something I’ll do on a rainy day. Until then, remembering the --cached
or --staged argument gets the job done!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.