如何使用git add仅暂存修改文件?忽略新增及删除文件
Great question! You’re exactly right that git add -u stages both modified and deleted files, while git add --ignore-removal covers modified and newly added files. Neither gives you the precise behavior you want: only staging files that have been modified, excluding any new or deleted ones.
Here’s the straightforward solution using Git’s built-in filtering capabilities:
The Command
To stage only modified files, run this command:
git add $(git diff --name-only --diff-filter=M)
Breakdown of the Command
Let’s break down what each part does:
git diff --name-only --diff-filter=M: This outputs the names of only modified files (theMin--diff-filter=Mstands for "modified"). The--name-onlyflag keeps the output clean, just listing filenames instead of full diff content.$(...): This is command substitution—Git takes the list of filenames from thegit diffcommand and passes them directly togit add, staging only those files.
Handling Filenames with Spaces
If your repository has filenames containing spaces, the above command might fail. For a more robust version, use xargs:
git diff --name-only --diff-filter=M | xargs git add
xargs safely handles spaces in filenames by splitting the input correctly.
Optional: Create a Git Alias
For convenience, you can add an alias to your Git config so you don’t have to type the full command every time. Run this to set up an alias called add-modified:
git config --global alias.add-modified '!git diff --name-only --diff-filter=M | xargs git add'
Now you can just run git add-modified whenever you want to stage only modified files.
内容的提问来源于stack exchange,提问作者Arvind Mohan

