How to Use git add: Basic Syntax and Examples
Use
git add to stage changes in your working directory before committing them. You can add specific files with git add filename or all changes with git add ..Syntax
The basic syntax of git add includes specifying the files or directories you want to stage for commit.
git add <file>: Adds a specific file.git add .: Adds all changes in the current directory and subdirectories.git add -A: Adds all changes including deletions.
bash
git add <file> git add . git add -A
Example
This example shows how to create a file, stage it with git add, and then check the status to confirm it is staged.
bash
echo "Hello Git" > example.txt
git add example.txt
git statusOutput
On branch main
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: example.txt
Common Pitfalls
Common mistakes include:
- Forgetting to stage files before committing, so commits have no changes.
- Using
git add .without checking, which may add unwanted files. - Not adding deleted files with
git add -A, so deletions are not recorded.
bash
git commit -m "Update" # Without git add, this commits nothing # Correct way: git add file.txt git commit -m "Add file.txt"
Quick Reference
| Command | Description |
|---|---|
| git add | Stage a specific file for commit |
| git add . | Stage all changes in current directory |
| git add -A | Stage all changes including deletions |
| git add -p | Interactively stage parts of files |
Key Takeaways
Use git add to stage files before committing changes.
git add . stages all changes in the current directory and below.
Use git add -A to include file deletions in staging.
Always check git status to see what is staged.
For partial changes, use git add -p to stage interactively.