A Detailed Guide to Adding Files to the Staging Area in Git

The staging area is a unique concept in Git; it sits between the working directory and the repository, allowing you to precisely control the contents of each commit. The git add command adds changes to the staging area.

1. Overview of git add

(1) What is a temporary storage area?

The staging area is a key component of Git's three-zone model:

100%
graph TB
    subgraph GitThe Three-Zone Model
        W[Workspace<br/>Working Directory<br/>Files Actually Edited]
        S[Buffer<br/>Staging Area<br/>Changes Ready to Be Submitted]
        R[Repository<br/>Repository<br/>All Commit History]
    end
    
    W -->|git add| S
    S -->|git commit| R
    R -->|git checkout| W
    
    style W fill:#fff3cd
    style S fill:#d4edda
    style R fill:#c3e6cb

(2) Why is a buffer needed?

The staging area provides fine-grained commit control:

Advantage Description Example
Selective Commits Not all changes need to be committed Commit only files that fix bugs; do not commit experimental code
Submit in batches Submit different changes separately Submit Feature A and Feature B separately
Change Review Pre-commit checks Verify that the staged changes are correct
Undo Changes Undoing a staged change does not affect the working directory You can undo changes to a staged file

(3) The Purpose of git add

The git add command copies changes from the working directory to the staging area:


2. Add Process

(1) Basic Syntax

BASH
# Add a Single File
git add <File Name>

# Add Multiple Files
git add <Documents1> <Documents2> <Documents3>

# Add all files in the directory
git add <Directory Name>

# Add all files in the current directory
git add .

(2) Detailed Explanation of the Add Process

100%
sequenceDiagram
    participant W as Workspace
    participant S as Buffer
    participant R as Repository
    
    Note over W: Document Status: Modified/Untracked
    
    W->>S: git add <file>
    Note over S: Copy the file to the temporary storage area<br/>CalculationSHA-1Hash<br/>Update Index
    
    Note over S: Document Status: Staged
    
    S->>R: git commit
    Note over R: Document Status: Committed

(3) Changes After Addition

After adding a file to the staging area:

▶ Example: Adding a Single File

BASH
# Create a New File
echo "# My Project" > README.md

# View Status(Not tracked)
git status
# Untracked files:
#   README.md

# Add to Stash
git add README.md

# View Status(Saved)
git status
# Changes to be committed:
#   new file:   README.md

# View the contents of the staging area
git diff --staged
# diff --git a/README.md b/README.md
# new file mode 100644
# index 0000000..e69de29
# --- /dev/null
# +++ b/README.md
# @@ -0,0 +1 @@
# +# My Project

▶ Example: Adding Multiple Files

BASH
# Create Multiple Files
echo "console.log('app');" > app.js
echo "console.log('test');" > test.js
echo "node_modules/" > .gitignore

# Add Multiple Files
git add app.js test.js .gitignore

# View Status
git status -s
# A  .gitignore
# A  app.js
# A  test.js

# Or add them one by one
git add app.js
git add test.js
git add .gitignore

# The results are the same

3. Add Options

(1) Batch Add Method

Git offers several ways to add files in bulk:

BASH
# Add all files in the current directory(Excludes deletions)
git add .

# Add all modifications and deletions to tracked files
git add -u

# Add All Files (Including new files, Edit, Delete)
git add -A
# Or
git add --all

# Interactive Addition(Verify one by one)
git add -p

(2) Comparison of Options

Command New Files Modified Deleted Scope
git add <文件> Specify file
git add . Current Directory
git add -u Entire repository
git add -A Entire repository

(3) Interactive Addition

git add -p (patch mode) allows you to review each modification block one by one:

BASH
git add -p
# Show Modified Blocks,Ask if you want to save a draft
# Stage this hunk [y,n,q,a,d,e,?]?
# y - yes,Temporarily store this block
# n - no,Do not cache
# q - quit,Exit
# a - all,Cache all blocks in this file
# d - discard,Do not cache any blocks from this file
# e - edit,Edit this block manually
# ? - help,Show Help

▶ Example: Adding Comparisons in Bulk

BASH
# Create a Scene
echo "new file" > new.txt          # New Document
echo "content" > tracked.txt
git add tracked.txt
git commit -m "Add tracked"
echo "modified" >> tracked.txt     # Modified
git rm tracked.txt                 # Delete(Simulation)

# Usage git add .
git add .
git status -s
# A  new.txt
# (Do not process deletion)

# Reset
git reset

# Usage git add -u
git add -u
git status -s
# D  tracked.txt
# (Process only modifications and deletions to tracked files)

# Reset
git reset

# Usage git add -A
git add -A
git status -s
# A  new.txt
# D  tracked.txt
# (Process all)

4. Buffer Management

(1) View the contents of the staging area

BASH
# View Staged Changes
git diff --staged
# Or
git diff --cached

# View the differences between the staging area and the repository
git diff --staged HEAD

# View the list of files in the staging area
git status

(2) Characteristics of the Buffer

Key Features of the Buffer:

100%
graph TB
    A[Workspace Files] -->|git add| B[Swap Area Snapshot]
    B -->|git commit| C[Repository Commit]
    
    A -->|Continue editing| D[New Version of the Workspace]
    D -->|git add| E[Update the temporary storage area]
    
    B -.->|Different Versions| D
    
    style B fill:#d4edda
    style D fill:#fff3cd

Key Points:

(3) Overwriting the Temporary Storage Area

Repeating git add will overwrite the contents of the clipboard:

BASH
# First time adding
echo "version 1" > file.txt
git add file.txt
# Buffer:version 1

# Edit File
echo "version 2" > file.txt
# Workspace:version 2
# Buffer:version 1(Unchanged)

# Add Again
git add file.txt
# Buffer:version 2(Updated)

▶ Example: Separating the Staging Area from the Working Area

BASH
# Create and Add Files
echo "Line 1" > file.txt
git add file.txt

# View the contents of the staging area
git diff --staged
# +Line 1

# Continue editing the file
echo "Line 2" >> file.txt

# View the differences between the workspace and the staging area
git diff
# +Line 2

# View Status
git status -s
# AM file.txt
# A:The temporary storage area contains data(Line 1)
# M:There are new changes in the workspace(Line 2)

# Update the temporary storage area
git add file.txt

# The staging area currently contains all changes.
git diff --staged
# +Line 1
# +Line 2

5. Undo Addition

(1) Undo Stash

If you've staged the wrong file, you can unstage it:

BASH
# Undo Staging for a Single File(New Grammar)
git restore --staged <File Name>

# Undo Staging for a Single File(Old Syntax)
git reset HEAD <File Name>

# Uncheck all checkboxes
git restore --staged .
# Or
git reset

(2) Status After Revocation

After undoing the staging:

(3) Revoke vs. Discard

Be sure to distinguish between these two operations:

100%
graph TB
    A[Saved Files] -->|git restore --staged| B[Undo Temporary Save<br/>Workspace Retained]
    A -->|git restore| C[Discard Changes<br/>Revert to the version in the staging area]
    
    B --> D[Status: Untracked/Modified]
    C --> E[Status: Staged]
    
    style B fill:#d4edda
    style C fill:#f8d7da

▶ Example: Undoing a staging operation

BASH
# Create and Add Files
echo "test content" > test.txt
git add test.txt
git status -s
# A  test.txt

# Undo Temporary Save
git restore --staged test.txt
git status -s
# ?? test.txt
# The file has reverted to an untracked state

# Undo for Tracked Files
echo "# Project" > README.md
git add README.md
git commit -m "Add README"

echo "new content" >> README.md
git add README.md
git status -s
# M  README.md

# Undo Temporary Save
git restore --staged README.md
git status -s
#  M README.md
# The file reverts to its modified state,Changes Retained

▶ Example: Adding a Scene Interactively

BASH
# Create a file containing multiple changes
cat > app.js << 'EOF'
function oldFunction() {
  console.log('old');
}

function newFeature() {
  console.log('new feature');
}

function debugCode() {
  console.log('debug');  // Temporary Debugging Code
}
EOF

git add app.js
git commit -m "Add app"

# Edit File:Includes feature improvements and debugging code
cat > app.js << 'EOF'
function oldFunction() {
  console.log('old');
  console.log('improved');  // Feature Improvements
}

function newFeature() {
  console.log('new feature');
  console.log('enhanced');  // Feature Enhancements
}

function debugCode() {
  console.log('debug');  // Temporary Debugging Code
}
EOF

# Use Interactive Add,Improvements to the Temporary Storage Feature
git add -p
# Confirm each modification block one by one
# y - Improvements to the Temporary Storage Feature
# n - Do not cache debug code

# Submit Feature Improvements
git commit -m "Improve features"

# The debugging code is still in the workspace,Not submitted

❓ FAQ

Q What is the difference between git add . and git add -A?
A git add . only processes files in the current directory and its subdirectories; it does not include deletions from other directories. git add -A processes all files in the entire repository, including additions, modifications, and deletions in all directories. The two commands have the same effect in the repository root directory, but there is a difference when used in subdirectories.
Q What happens if I continue editing the file after staging it?
A The file will appear in both the staging area and the working directory, but their contents will differ. The staging area contains the version as it was when added, while the working directory contains the new version after editing. The status will be displayed as AM or MM. You need to use git add to update the staging area again, or commit the staging area contents before adding new changes.
Q How do I view the contents of the clipboard?
A Use git diff --staged or git diff --cached to view the changes in the staging area. This will show the differences between the staging area and the last commit. If you want to view the contents of specific files, use git show :filename to view the files in the staging area.
Q Does git add overwrite content that has already been staged?
A Yes. Running git add again on the same file will update the contents of the staging area to the latest version. This is the normal way to update the staging area; it is not a problem but a feature.
Q How can I apply only some of the changes to a file?
A Use git add -p to enter interactive mode. Git will display the changes one hunk at a time, and you can choose "y" to stage, "n" to skip, or "e" to edit manually. This allows you to precisely control which changes are staged, enabling you to commit different changes in a single file separately.

📖 Summary


📝 Exercises

  1. Basic Exercise: Create a Git repository, add multiple files to the staging area, use git diff --staged to view the staged content, and then commit. Observe the changes in status at each step.

  2. Advanced Exercise: Create a file, add it to the staging area, and continue editing it. Observe the differences between the working directory and the staging area. Try using the git add -p interactive add command to stage only a portion of the changes.

  3. Challenge: Simulate a real-world scenario: You’ve fixed two bugs, added a new feature, and written some temporary debugging code. Use interactive commits and multiple commits to keep different changes separate and maintain a clear commit history.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏