如何在 Git 中交互式添加未跟踪文件?

How to interactively add untracked file in Git?

我经常使用 git add -p 在 Git 中分段提交文件,但这对未跟踪的文件不起作用:

$ git add -p file
No changes.

我怎样才能添加这个文件,而不是暂存所有文件?

我只想添加其中的一部分并提交,其余的不暂存。

您可以分两步完成此操作:

  1. git add -N file

来自man page

-N, --intent-to-add Record only the fact that the path will be added later. An entry for the path is placed in the index with no content. This is useful for, among other things, showing the unstaged content of such files with git diff and committing them with git commit -a.

此命令会将文件添加为空,因此不会再取消跟踪,但 none 的文件仍会暂存。

# Initial commit
#
# Changes to be committed:
#   (use "git rm --cached <file>..." to unstage)
#
#   new file:   file
#
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   file
#
  1. git add -p file

现在文件已被跟踪,git add -p 正常工作。