📅  最后修改于: 2023-12-03 15:00:55.039000             🧑  作者: Mango
Git is a powerful tool for version control of code. When working with Git, you will frequently use the git add
command to add changes to the staging area. However, there may be times when you want to add all files except a few files or directories. In this guide, we will explore how to git add
except files.
git add
CommandBefore we dive into adding except files, let's briefly review the git add
command. This command is used to add changes to the staging area. The staging area acts as a buffer between your working directory and the repository. You can think of it as a place where you can carefully curate the changes you want to commit.
To add all changes, you can use the following command:
git add .
This will add all changes in the current directory and its subdirectories to the staging area.
If you want to add a specific file, you can specify the path to that file:
git add path/to/file
.gitignore
If there are files or directories that you never want to add to Git, you can exclude them using a .gitignore
file. This file contains a list of patterns for files and directories to be ignored. When you add the --ignore-unmatch
flag to the git add
command, Git will exclude files and directories matching any patterns in your .gitignore
file.
Add a .gitignore
file to your repository and add the files and directories you want to ignore. Here's an example of a .gitignore
file that excludes node_modules
and .DS_Store
:
node_modules/
.DS_Store
Now, when you run git add . --ignore-unmatch
, Git will exclude these files and directories from being added to the staging area.
If you need to add all files except a few, you can use the following command:
git add $(git ls-files | grep -v path/to/file | tr '\n' ' ')
This command uses git ls-files
to list all the files in the repository, grep -v
to exclude files matching path/to/file
, and tr '\n' ' '
to translate the output to a single line of space-separated files.
Replace path/to/file
with the path to the file or directory you want to exclude. You can also exclude multiple files and directories by separating them with |
.
The git add
command is a powerful tool for staging changes before committing them to the repository. With .gitignore
and a few command-line tricks, you can easily exclude files and directories from being added to the staging area. Now that you know how to git add
except files, you will have more control over which changes you commit to your repository.