高效地将项目添加到Git索引中

3

我发现将更改的文件添加到索引时写完整路径非常繁琐。例如,我更改了3个文件,但只想提交其中的2个:

# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   apps/frontend/config/modules/file1
#   modified:   apps/frontend/config/modules/file2
#   modified:   apps/frontend/config/modules/file3

所以我必须输入这么多:

git add app/frontend/modules/file1 app/frontend/modules/file3

我正在寻找一种通过索引在git状态列表中添加项目的方法?类似于:
git add %1 %3
4个回答

4

使用 interactive 命令添加:

git add -i

它会为每个文件询问您是否要将其添加到提交中。

您甚至可以基于补丁进行选择,这总是非常有用的:

git add -p

2
cd apps/frontend/config/modules
git add file1 file3
cd - #go back

请注意,“cd -”是特定于shell的。(即,它不适用于所有shell) - William Pursell
@WilliamPursell cd - 是 POSIX 中的命令。哦,你在用 csh?那么,请使用 pushdpopd 命令。 - Gilles 'SO- stop being evil'
@Giles,我没有意识到它是POSIX,并认为它是一个bashism。谢谢你指出来! - William Pursell

2
您也可以使用shell扩展: git add app/frontend/modules/file{1,3}

1

我一直在使用我编写的类似脚本来添加仅一个文件,例如git nadd N来添加第N个修改的文件。将其修改为允许添加多个文件应该不难。

#!/bin/bash

if [[ $# != 1 ]] ; then
    echo "usage: git nadd <index>"
    exit 0
fi

num=$1

# get unstaged modified files
modified_files=$(git status --porcelain | grep " M " | cut -c 4-)

if [[ $modified_files == "" ]] ; then
    echo "error: there are no modified files"
    exit 1
fi

# count how many we have
num_modified_files=$(echo "$modified_files" | wc -l)

if [[ $num -gt $num_modified_files ]] ; then
    echo "error: index larger than number of modified files"
    exit 2
fi

# pick n'th modified file
file=$(echo "$modified_files" | sed -n "$num p")

# fix $file to full path in case we're not in root
root=$(git rev-parse --show-cdup)
file=$root$file

git add -- "$file"

使用数组:modified_files=($(...))num_modified_files=${#modified_files[@]}file=${modified_files[num]}。此外,您可以执行 if (( num > num_modified_files )) - Dennis Williamson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接