首页 > 解决方案 > 在 git 中暂存文件(使用终端)时,是否有命令/快捷方式仅将某些文件添加到 INDEX?

问题描述

例如,如果我有 8 个不同的文件需要提交,但其中 4 个我想一起提交,我怎样才能只添加这 4 个而无需输入完整路径或复制/粘贴?

编辑:更具体地说,我正在寻找一种从编号列表中进行选择的方法:

假的例子:

Git status

File.txt
File.txt
File.txt
File.txt
File.txt
File.txt

Git add 1,3,6

标签: gitterminal

解决方案


这取决于文件的名称。如果有一种模式可用于明确标识要添加的文件,您可以使用glob来指定带有git add.

一个例子:

$ git status
On branch master

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        file1.txt
        file2.txt
        file3.txt
        file4.txt
        file5.txt
        file6.txt
        file7.txt
        file8.txt

nothing added to commit but untracked files present (use "git add" to track)
$ git add file[1-4].txt
$ git status
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

        new file:   file1.txt
        new file:   file2.txt
        new file:   file3.txt
        new file:   file4.txt

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        file5.txt
        file6.txt
        file7.txt
        file8.txt

或者,您可以使用git add --interactive

$ git add --interactive

*** Commands ***
  1: status       2: update       3: revert       4: add untracked
  5: patch        6: diff         7: quit         8: help
What now> 4
  1: file1.txt
  2: file2.txt
  3: file3.txt
  4: file4.txt
  5: file5.txt
  6: file6.txt
  7: file7.txt
  8: file8.txt
Add untracked>> 1-4
* 1: file1.txt
* 2: file2.txt
* 3: file3.txt
* 4: file4.txt
  5: file5.txt
  6: file6.txt
  7: file7.txt
  8: file8.txt
Add untracked>>
added 4 paths

*** Commands ***
  1: status       2: update       3: revert       4: add untracked
  5: patch        6: diff         7: quit         8: help
What now> 7
Bye.
$ git status
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

        new file:   file1.txt
        new file:   file2.txt
        new file:   file3.txt
        new file:   file4.txt

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        file5.txt
        file6.txt
        file7.txt
        file8.txt

推荐阅读