git add
Description:
Add file contents to the staging area (index), preparing them for the next commit. This tells Git which changes you want to include.
Syntax:
bash
git add <file>
git add <directory>
git add .
git add -A
git add -pExamples:
bash
# Add a specific file
git add index.html
# Add all files in a directory
git add src/
# Add all changes in current directory and subdirectories
git add .
# Add all changes in entire repository
git add -A
# Interactively choose which changes to add
git add -p style.cssDetailed Explanation:
- Staging area:
git addmoves changes to the staging area, a middle ground between working directory and repository - Snapshot: Creates a snapshot of the current file content that will be committed
- Selective adding: You can add only specific files or even specific lines within files (
-p) - Doesn't commit: Files added are not yet saved to history until you run
git commit
Common Errors:
fatal: pathspec 'file' did not match any files→ Solution: Check file path spelling or if file existswarning: LF will be replaced by CRLF→ Solution: This is line-ending normalization, usually safe to ignore- Nothing happens after
git add→ Solution: This is normal; usegit statusto verify files are staged
Pro Tips:
- Use
git add -pfor interactive staging (great for committing only parts of a file) - Use
git add -uto stage only modified and deleted files (not new files) - Use
.gitignoreto prevent accidentally adding unwanted files - Review staged changes with
git diff --stagedbefore committing - Warning:
git add .adds everything in current directory; double-check withgit statusfirst
Related Commands:
git status– See what's staged and unstagedgit commit– Save staged changes to historygit reset– Unstage filesgit diff– See what changes are staged