Q5 of 40 · Git
What does `git add` actually do?
Short answer
Short answer: git add copies the current state of a file from the working directory into the staging area (the index). It doesn't write anything permanent — it builds the snapshot that git commit will capture. git add -p lets you stage specific hunks of a file, giving fine-grained control over each commit's content.
Detail
The staging area (also called the index) is a file in .git/index that records the exact state of each file that the next git commit will snapshot. git add updates that index to match the working-directory version of the specified files.
Key behaviours:
git add file.txt— stage exactly the current version offile.txtgit add -p— interactive hunk selection: stage part of a file while leaving the rest unstaged. Essential for clean commits when you've made multiple unrelated changes to one file.git add .— stage all changes in the current directory tree (commonly misused as a "stage everything" shortcut)
Why Git has a staging area: it lets you build the perfect commit even when your working directory contains work-in-progress. You can have a test file with 3 different changes and stage only the fix-related hunk, keeping the other changes out of that commit.
// EXAMPLE
# Stage one specific file
git add tests/UserApiTest.java
# Stage all modified and deleted files (NOT untracked)
git add -u
# Stage everything — use with care (may include unintended files)
git add .
# Interactive staging — choose which hunks to include
git add -p tests/UserApiTest.java
# Shows each diff hunk; respond y (stage), n (skip), s (split), e (edit)
# Verify what's staged vs unstaged
git diff --staged # staged: what the next commit will include
git diff # unstaged: changes NOT yet staged