Track new files (git add)
Tracking New Files (git add)
One of Git's core functionalities is tracking file changes. When you create new files in your project or modify existing ones, Git does not automatically record these changes. You need to explicitly tell Git which files should be included in version control. This is the purpose of the git add
command.
Basic Usage of git add
The git add
command is used to add files to the staging area. The staging area is an intermediate zone in Git's workflow that allows you to carefully select which changes to include in the next commit before making the commit.
The most basic usage is to add a single file:
git add filename.txt
You can also add multiple files by listing them sequentially:
git add file1.txt file2.txt file3.js
Adding All New and Modified Files
If you want to add all new and modified files at once (excluding deleted files), you can use:
git add .
The .
represents the current directory and all its subdirectories. This command recursively adds all new and modified files.
If you also want to include deleted files, you can use the -A
or --all
option:
git add -A
Interactive Adding
Git provides an interactive mode that allows for finer control over which changes to stage:
git add -i
Or, using a more modern interactive interface:
git add -p
The -p
or --patch
option lets you review changes one by one and decide whether to stage them. This is particularly useful for large modifications, as you can break down a single large change into multiple logically independent commits.
Adding Partial Changes to a File
Sometimes, you may want to stage only part of the changes in a file rather than the entire file. Git allows you to do this:
git add -p filename.js
This opens an interactive interface showing each chunk of changes in the file. For each chunk, you can choose:
- y: stage this chunk
- n: do not stage this chunk
- q: quit
- a: stage this chunk and all remaining chunks in the file
- d: do not stage this chunk and all remaining chunks in the file
- /: search for a chunk matching a regular expression
- s: split the current chunk into smaller chunks
- e: manually edit the current chunk
- ?: show help
Undoing Staged Changes
If you accidentally stage unwanted files, you can unstage them using:
git reset HEAD filename.txt
Or unstage all staged changes:
git reset
Handling Special Cases
Adding Empty Directories
Git does not track empty directories. If you want to preserve an empty directory in the repository (usually to maintain the directory structure), you can create an empty .gitkeep
file in the directory:
mkdir empty_directory
touch empty_directory/.gitkeep
git add empty_directory/.gitkeep
Adding Large Files
For large files, it is generally recommended to use Git LFS (Large File Storage) instead of adding them directly to Git:
git lfs track "*.psd"
git add .gitattributes
git add file.psd
Ignoring Tracked Files
If you want to stop tracking a file but keep it in the local working directory:
git rm --cached filename.txt
This removes the file from Git's tracking list but does not delete the physical file.
Practical Examples
Suppose we have a front-end project with the following structure:
project/
├── index.html
├── css/
│ └── style.css
└── js/
└── app.js
Scenario 1: Adding a Newly Created File
You just created a new JavaScript file:
touch js/utility.js
git add js/utility.js
Scenario 2: Adding Modified Files
You modified a CSS file:
git add css/style.css
Or add all modified files:
git add .
Scenario 3: Interactive Adding
You made multiple changes to app.js
but want to commit them separately:
git add -p js/app.js
In the interactive interface, you can selectively stage relevant changes.
Usage in Automation Scripts
In automation scripts, you may need more precise control over git add
behavior. For example, in a deployment script:
#!/bin/bash
# Only add built files
git add -f dist/*
# Or add specific file types
git add *.html *.css *.js
Troubleshooting Common Issues
Added the Wrong File
If you accidentally added the wrong file, you can undo it:
git reset HEAD wrongfile.txt
File Is Ignored but Still Added
If a file is in .gitignore
but still gets added, it may have been tracked previously. Force Git to ignore it:
git rm --cached file-to-ignore
Permission Changes Detected as Modifications
Git detects file permission changes. If you don't care about permission changes, configure:
git config core.fileMode false
Advanced Tips
Using Wildcards
You can use wildcards to add specific file types:
git add *.js
Adding All Files Except Certain Ones
Use the :(exclude)
syntax:
git add . ":(exclude)*.log"
Previewing What Will Be Added
Before actually adding, you can preview which files will be added:
git add -n .
Integration with Other Commands
git add
is often used with the following commands:
git add .
git commit -m "Description"
git push
Or in a more complex workflow:
git add -p
git commit -m "Partial changes"
git add .
git commit -m "Remaining changes"
Performance Considerations
For large repositories, git add .
can be slow. In such cases:
- Only add necessary files
- Use
.gitignore
to exclude unwanted files - Consider using
git add -u
to add only tracked files
Best Practices
- Small, Frequent Commits: Add and commit small, logically independent changes frequently.
- Review Changes: Use
git diff
to review changes before adding. - Use Interactive Mode: Especially when a single modification involves multiple unrelated changes.
- Keep the Staging Area Clean: Only add changes that are ready to commit.
- Leverage .gitignore: Avoid accidentally adding unwanted files.
Comparison with Other Version Control Systems
Unlike SVN, Git's add
command is not mandatory (in SVN, you must svn add
after creating a new file). Git's add
is more about selecting what to commit rather than declaring which files to track.
Underlying Principles
When you run git add
, Git:
- Calculates the file's SHA-1 hash
- Stores the file content in the
.git/objects
directory - Updates the index (
.git/index
file) to record the file's state
This explains why git add
is sometimes referred to as "staging a file" or "adding a file to the index."
Warnings About Dangerous Operations
git add .
adds all files, including potentially large files or sensitive information.- Added files will be included in the next commit and may be pushed to the remote repository.
- Be especially careful not to add passwords, keys, or personal information.
Practical Case: Front-End Project Workflow
Suppose you're developing a React application:
- Create a new component:
touch src/components/NewComponent.js
- After writing the component code, add it:
git add src/components/NewComponent.js
- Modify an existing component and styles:
git add -p src/components/ExistingComponent.js
git add src/styles/main.css
- Prepare to commit:
git commit -m "Add new component and update styles for existing component"
Automated Linting and Adding
You can set up a pre-commit hook to automatically run linting when adding files:
#!/bin/sh
npm run lint
git add .
Handling Post-Merge Conflict Adding
After resolving merge conflicts, you need to add the resolved files:
git add conflicted-file.js
Usage in GUI Tools
Most Git GUI tools (e.g., GitHub Desktop, GitKraken) provide a visual way to stage files, typically via checkboxes to select which changes to stage.
Batch Operations
You can combine multiple Git commands:
git add . && git commit -m "Batch add and commit"
Or more complex operations:
git add src/ && git commit -m "Add source files" && git add tests/ && git commit -m "Add tests"
File State Lifecycle
Understanding git add
requires knowledge of Git's file state lifecycle:
- Untracked: New file, not yet tracked by Git
- Modified: Tracked file that has been modified
- Staged: Changes staged via
git add
- Committed: Changes committed via
git commit
git add
transitions files from untracked or modified to staged.
Environment Variable Impact
Certain environment variables can affect git add
behavior:
GIT_EDITOR=nano git add -p # Use nano as the editor for interactive editing
Cross-Platform Considerations
Windows and Unix-like systems handle file paths and line endings differently. Git can automatically handle these differences:
git config --global core.autocrlf true # Windows
git config --global core.autocrlf input # Linux/Mac
Debugging git add
If git add
behaves unexpectedly, you can enable tracing:
GIT_TRACE=1 git add .
Plugins and Extensions
Some Git plugins enhance git add
functionality, such as git-extras
's git add-from
, which can add files from another branch.
Historical Evolution
The functionality of git add
has been enhanced across different Git versions. For example, newer versions have improved the user experience of the interactive mode (-p
).
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
下一篇:暂存已修改文件