You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用git add仅暂存修改文件?忽略新增及删除文件

How to Stage Only Modified Files (Ignore New/Deleted) in Git

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 (the M in --diff-filter=M stands for "modified"). The --name-only flag keeps the output clean, just listing filenames instead of full diff content.
  • $(...): This is command substitution—Git takes the list of filenames from the git diff command and passes them directly to git 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:13:32