我用:

git checkout -b testbranch

我做了20次提交。

现在我想要压缩这20个提交。我是这样做的:

git rebase -i HEAD~20

如果我不知道有多少次提交呢?有没有什么方法可以做到:

git rebase -i all on this branch

当前回答

git checkout -b temp
git checkout yourbranch
git fetch
git reset --hard origin/master
git merge --squash temp
git commit -m "new message" 

最简单的方法。

这将创建一个新的分支,然后将你的分支重置为基础分支,然后在将临时分支合并回我们的分支之前,我们压缩更改并创建一个新的提交

其他回答

你正在做的事情很容易出错。只做:

git rebase -i master

它会自动将你的分支的提交重置到当前最新的主节点上。

由于我在这里提出的解决方案中遇到了一些麻烦,我想分享一个非常简单的解决方案(无论如何都是有效的):

git merge origin/master && git reset --soft origin/master

前面的合并cmd确保,在提交时,没有来自master的最近更改会出现在你的头上(倒置)!之后,只需提交更改并执行git push -f

签出您希望将所有提交压缩为一次提交的分支。我们说它叫feature_branch。

git checkout feature_branch

步骤1:

用你的本地主分支对你的origin/feature_branch进行软重置(根据你的需要,你也可以用origin/main重置)。这将重置feature_branch中所有额外的提交,但不会在本地更改任何文件更改。

git reset --soft main

步骤2:

将git repo目录中的所有更改添加到将要创建的新提交中。并通过信息提交相同的信息。

# Add files for the commit.
git add ...
git commit -m "commit message goes here"

Git重置,正如之前在许多回答中提到的,是迄今为止实现你想要的最好和最简单的方法。我在以下工作流程中使用它:

(有关发展分支)

git fetch
git merge origin/master  #so development branch has all current changes from master
git reset origin/master  #will show all changes from development branch to master as unstaged
git gui # do a final review, stage all changes you really want
git commit # all changes in a single commit
git branch -f master #update local master branch
git push origin master #push it

我知道这个问题已经有了答案,但我围绕已接受的答案编写了一个bash函数,以允许您在一个命令中完成它。它首先创建一个备份分支,以防压缩由于某种原因失败。然后压缩并提交。

# Squashes every commit starting after the given head of the given branch.
# When the squash is done, it will prompt you to commit the squash.
# The head of the given parent branch must be a commit that actually exists
# in the current branch.
#
# This will create a backup of the current branch before it performs the squash.
# The name of the backup is the second argument to this function.
#
# Example: $ git-squash master my-current-branch-backup
git-squash() {
  PARENT_BRANCH=$1
  BACKUP_BRANCH=$2

  CURRENT_BRANCH=$(git branch --show-current)

  git branch $BACKUP_BRANCH
  BACKUP_SUCCESS=$?

  if [ $BACKUP_SUCCESS -eq 0 ]; then
    git reset $(git merge-base $PARENT_BRANCH $CURRENT_BRANCH)
    git add -A
    git commit
    echo "Squashed $CURRENT_BRANCH. Backup of original created at $BACKUP_BRANCH$"
  else
    echo "Could not create backup branch. Aborting squash"
  fi
}