乐闻世界logo
搜索文章和话题

How do I delete unpushed git commits?

1个答案

1

In Git, if you want to remove commits that haven't been pushed to the remote repository, you can use several methods to achieve this. Here are two common approaches:

Method 1: Using git reset

Suppose you want to remove the most recent commits; you can use the git reset command. This command moves the HEAD pointer to a specified state, allowing you to choose modes that determine whether to retain changes.

  • Soft Reset:

    bash
    git reset --soft HEAD~N

    Here, N represents the number of commits to revert. This command reverts to the state before the specified commit without altering the working directory files. Changes made prior to the commit remain in the staging area, enabling you to modify and recommit them.

  • Hard Reset:

    bash
    git reset --hard HEAD~N

    This command discards the last N commits and reverts all changes in the working directory. Use hard reset with caution, as it will lose all uncommitted changes.

Example: If you realize that the most recent two commits contain errors and have not been pushed to the remote repository, execute git reset --hard HEAD~2 to revert these commits and clear all related changes.

Method 2: Using git rebase

If you need to more precisely delete or modify specific commits, you can use the git rebase command.

  • Interactive Rebase:
    bash
    git rebase -i HEAD~N
    Here, N represents the number of commits to go back from the current commit. This command opens an interactive interface where you can select commits to operate on. For instance, you can use drop to remove a commit or edit to modify a commit.

Example: To delete the third most recent commit, execute git rebase -i HEAD~3, then in the opened text editor, locate the commit, change the command from pick to drop, save, and exit. Git will apply this change and rewrite history.

When using these commands, please note:

  • These operations modify history; when used in a team, ensure your colleagues are aware of the changes.
  • Use these commands only if the commits have not been pushed to the remote repository. If they have been pushed, use alternative strategies like git revert or git push --force after pushing, but this should be a last resort.
2024年6月29日 12:07 回复

你的答案