Skip to main content

Git Command

Filter-branch

如果要批量更新过去的commit, 可以用git filter-branch:

--env-filter可以把committer和author的信息改掉,而

--msg-filter可以修改commit message

#!/bin/bash


git filter-branch -f --env-filter '

OLD_EMAIL="***@***.com"

CORRECT_NAME="your_name"

CORRECT_EMAIL="your_email@example.com"

if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]

then

​ export GIT_COMMITTER_NAME="$CORRECT_NAME"

​ export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"

fi

if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]

then

​ export GIT_AUTHOR_NAME="$CORRECT_NAME"

​ export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"

fi

' --tag-name-filter cat \

--msg-filter 'sed "s/Signed-off-by:.*/private commit/g"'


Git rebase -i

这也是一个很有用的工具,可以squash过去的commits. 有些时候,这对保护隐私也很有用,因为删掉的代码在git history里也是有记录的,有些时候test的时候偷懒就将一些credential写在代码里了,就可以用这种方式去squash掉记录。

当然,正经的用法是集成在CI/CD里了,目的是将若干个commit合并,避免git history过于冗长,给开发合作造成困扰。

比如我想squash掉最近的5个commit:

git rebase -i HEAD~5

然后git会调用vi的编辑器,将最上边的commit改为pick,其余的commit为squash就可以了。