git diff --staged
- Version
- 2.51
- Review
- Draft
Summary#
git diff --staged compares the index with HEAD, showing the changes staged for the next commit. --cached is an equivalent flag.
Syntax#
git diff --staged
git diff --staged -- path/to/file
git diff --cached
Example#
(
set -eu
scratch=$(mktemp -d "${TMPDIR:-/tmp}/devlookup-git.XXXXXX")
trap 'rm -rf -- "$scratch"' EXIT
unset GIT_CONFIG_GLOBAL $(git rev-parse --local-env-vars)
export GIT_CONFIG_NOSYSTEM=1 GIT_TEMPLATE_DIR= LC_ALL=C
export HOME="$scratch" XDG_CONFIG_HOME="$scratch" GIT_ATTR_NOSYSTEM=1
mkdir "$scratch/work"
cd "$scratch/work"
git init -q -b trunk
git -c user.name="Reference Example" -c user.email=example@example.invalid commit --allow-empty -qm "Start"
printf 'alpha\n' > lines.txt
git add lines.txt
printf 'beta\n' > lines.txt
git --no-pager diff --staged -- lines.txt | sed -n '/^+alpha/p'
git --no-pager diff -- lines.txt | sed -n '/^+beta/p'
)
Expected output#
+alpha
+beta
Common mistakes#
Plain git diff shows working-tree changes relative to the index. Run both comparisons when a file has staged and unstaged changes. Before the first commit, git diff --staged shows all staged content.
Version applicability#
Git 1.6.1 added --staged as another spelling of --cached.
The complete example requires Git 2.28 or later for git init -b.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0