我有以下提交历史记录:

头部头部~头部~2头部~3

gitcommit--修改当前HEAD提交。但是如何修改HEAD~3?


当前回答

基于文档

修改旧的或多个提交消息的消息

git rebase -i HEAD~3 

上面显示了当前分支上最后3次提交的列表,如果需要更多,请将3更改为其他内容。列表将类似于以下内容:

pick e499d89 Delete CNAME
pick 0c39034 Better README
pick f7fde4a Change the commit message but push the same commit.

将pick替换为要更改的每个提交消息之前的改写。假设您更改了列表中的第二个提交,您的文件将如下所示:

pick e499d89 Delete CNAME
reword 0c39034 Better README
pick f7fde4a Change the commit message but push the same commit.

保存并关闭提交列表文件,这将弹出一个新的编辑器,供您更改提交消息、更改提交消息并保存。

最后,强制推行修改后的承诺。

git push --force

其他回答

如果您还没有推送提交,则可以使用git reset HEAD^[1,2,3,4…]返回到上一次提交

例如

git commit <file1> -m "Updated files 1 and 2"
git commit <file3> -m "Updated file 3"

抱歉,忘记在第一次提交时添加file2。。。

git reset HEAD^1 // because I only need to go back 1 commit

git add <file2>

这将在第一次提交时添加file2。

git存储+再基础自动化

因为当我需要多次修改Gerrit审查的旧提交时,我一直在做:

git-amend-old() (
  # Stash, apply to past commit, and rebase the current branch on to of the result.
  current_branch="$(git rev-parse --abbrev-ref HEAD)"
  apply_to="$1"
  git stash
  git checkout "$apply_to"
  git stash apply
  git add -u
  git commit --amend --no-edit
  new_sha="$(git log --format="%H" -n 1)"
  git checkout "$current_branch"
  git rebase --onto "$new_sha" "$apply_to"
)

GitHub上游。

用法:

修改源文件,如果已在repo中,则无需gitaddgit修改旧$old_sha

我很喜欢这一点,因为它不会挤压其他无关的修复。

如果出于某种原因,您不喜欢交互式编辑器,可以使用gitrebase--on。

假设您要修改Commit1。首先,从Commit1之前分支:

git checkout -b amending [commit before Commit1]

第二,用樱桃核抓取Commit1:

git cherry-pick Commit1

现在,修改您的更改,创建Commit1':

git add ...
git commit --amend -m "new message for Commit1"

最后,在隐藏了任何其他更改后,将其余的提交移植到master之上新提交:

git rebase --onto amending Commit1 master

阅读:“将Commit1(不包括在内)和master(包括在内)之间的所有提交重新纳入修改分支”。即Commit2和Commit3,将旧的Commit1完全删除。你可以随便摘,但这样更容易。

记得清理你的树枝!

git branch -d amending

Run:

$git rebase--交互式commit_hash^

每个^表示要编辑的提交次数,如果只有一个(指定的提交哈希),则只需添加一个^。

使用Vim,您可以更改要更改、保存和退出的提交的单词pick to reword(:wq)。然后git将提示您标记为reword的每个提交,以便您可以更改提交消息。

您必须保存并退出(:wq)以转到下一个提交消息的每个提交消息

如果要退出而不应用更改,请按:q!

编辑:要在vim中导航,请使用j向上,k向下,h向左,l向右(所有这些都在正常模式下,按ESC键转到正常模式)。要编辑文本,请按i以进入INSERT模式,在该模式下插入文本。按ESC返回正常模式:)

更新:这里有一个来自github的链接,列出了如何使用git撤消(几乎)任何操作

要获得非交互式命令,请在PATH中放置包含以下内容的脚本:

#!/bin/sh
#
# git-fixup
# Use staged changes to modify a specified commit
set -e
cmt=$(git rev-parse $1)
git commit --fixup="$cmt"
GIT_EDITOR=true git rebase -i --autosquash "$cmt~1"

使用它,先暂存更改(使用gitadd),然后运行gitfixup<commit to modify>。当然,如果您遇到冲突,它仍然是交互式的。