使用 git 以非交互方式编辑旧提交

Posted

技术标签:

【中文标题】使用 git 以非交互方式编辑旧提交【英文标题】:Editing old commits non-interactively with git 【发布时间】:2012-05-05 07:09:42 【问题描述】:

我知道如何手动编辑旧提交:

$ git log --pretty=format:'%h %s'
    60e5ed9 Second commit
    0fbc8ed First commit
$ git rebase --interactive 0fbc8ed # Going back to 'First commit'
    # * $EDITOR gets fired up *
    # change 'pick 0fbc8ed' to 'edit 0fbc8ed'
$ echo 'Hello Kitteh!' > some_file
$ git add some_file
$ git commit --amend -m 'some message'
$ git rebase --continue # Go back

这里的问题:

git rebase --interactive 会启动一个编辑器,这对脚本编写来说有点糟糕。有没有办法克服这个问题,即直接将edit 0fbc8ed 传递给git rebase 命令?

我的尝试是愚蠢的,还是有更清晰的替代方法?

有一个类似的问题,但就我而言,我想将pick 更改为edit

How can I automatically accept what git rebase --interactive presents to me?

【问题讨论】:

How can I easily fixup a past commit?的可能重复 【参考方案1】:

你可以在没有交互式变基的情况下做同样的事情:

git branch some_temporary_name # to save your initial place
git reset --hard commit_you_want_to_change
...edit...
git commit --amend -m 'some message'
git rebase your_initial_branch_name some_temporary_name
git checkout your_initial_branch_name
git merge some_temporary_name # This will be a ff since you rebased
git branch -d some_temporary_name # remove unneeded branch

【讨论】:

git commit --fixup 加上git rebase -i --autosquash 更好(再一次:)) @CharlesB -- 不会 git rebase -i --autosquash 仍然调出编辑器吗? 是的,但这只是为了检查它会做什么,通常你不需要编辑任何东西。干脆退出编辑器。将其视为确认对话框。 如上所述,您可以将EDITOR env-variable 设置为/bin/true 以自动接受它。【参考方案2】:

这是“git filter-branch”和选项“--commit-filter”的工作。看看手册页这里有一个示例部分。

【讨论】:

git commit --fixup 加上git rebase -i --autosquash 好多了 是的,你是对的,但是 --fixup 在你的消息前面加上一个“修复!” - 要么?你只能更改提交的主题行? 它是git commit --fixup <SHA-to-fix>,然后rebase -i --autosquash <SHA-to-fix>~1 用你正在修复的那个来压缩修复提交,奇迹发生了 这看起来很有希望。但是rebase -i 仍然生成编辑器?但我想我可以将EDITOR 设置为/bin/true 以自动接受它编辑:是的,这行得通。非常感谢!

以上是关于使用 git 以非交互方式编辑旧提交的主要内容,如果未能解决你的问题,请参考以下文章

如何以非交互方式在 Git 中重新排序提交

有没有办法以非交互方式压缩大量提交?

git修改提交信息

如何 git rebase -i 编辑并查看过去的提交更改

如何在不影响之后的提交的情况下编辑旧提交

Git:在以前的提交中删除旧模式 100644 新模式 100755