BudiBadu Logo
Samplebadu

Git by Example: Staging Changes

2.43.0

Master the concept of the staging area (index) in Git. Learn how to use git add to selectively prepare files for your next commit.

Code

# 1. Create/Modify files
echo "Draft content" > draft.txt
echo "Final content" > final.txt

# 2. Check status (both are untracked)
git status

# Output:
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#   draft.txt
#   final.txt

# 3. Stage ONLY the final file
git add final.txt

# 4. Check status again
git status

# Output:
# Changes to be committed:
#   (use "git restore --staged <file>..." to unstage)
#   new file:   final.txt
#
# Untracked files:
#   draft.txt

# 5. Commit only the staged changes
git commit -m "Add final report"

Explanation

The staging area (also known as the "index") is one of Git's most powerful and unique features. It acts as an intermediate holding zone between your working directory (where you edit files) and the repository history (where commits live). Unlike other version control systems where you simply "commit all changes," Git forces you to explicitly "add" changes to the staging area first.

This two-step process—git add then git commit—gives you precise control over your history. It allows you to group related changes into logical commits, even if you've edited multiple files for different reasons. For example, you can stage and commit a bug fix in one file while leaving a half-finished feature in another file uncommitted in your working directory.

The git add command moves changes from the working directory to the staging area. You can add individual files, entire directories, or use wildcards. Once files are staged, they are "ready to be committed." If you modify a staged file again before committing, you must run git add again to update the staged version.

  • Acts as a "draft" space for your next commit
  • Allows for selective, logical commits
  • git add moves changes to the staging area
  • Only staged changes are included in git commit

Code Breakdown

6
git status is crucial here. It shows that Git sees the new files but is not tracking them yet. They are "Untracked".
15
git add final.txt moves only this specific file into the staging area. The file draft.txt is intentionally left behind.
28
The commit command captures a snapshot of the staging area, not the working directory. Therefore, only 'final.txt' is saved in the history.