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

How can I revert multiple Git commits?

1个答案

1

Recovering multiple commits in Git can be done in various ways. The method you choose depends on your specific goals. Here are several common scenarios and recovery methods:

1. Using git revert for Bulk Reversion

If you want to undo the effects of a series of commits on the codebase while preserving the reversion records in history, you can use the git revert command. For example:

shell
git revert <commit-hash-1>^..<commit-hash-2>

In this command, ^ indicates that <commit-hash-1> is included but <commit-hash-2> is excluded.

Example:

Assume you have made three consecutive commits with hash values abc123, def456, and ghi789, and you now want to undo these three commits. You can do it as follows:

shell
git revert abc123^..ghi789

git revert creates new commits for each commit to be undone. If you encounter merge conflicts during execution, resolve them manually and then continue with git revert --continue.

2. Creating a New Branch

If you want to discard a series of commits and start new work from a specific commit, you can create a new branch:

shell
git checkout -b <new-branch-name> <commit-hash>

Example:

If you want to discard the latest few commits and start working anew, you can do:

shell
git checkout -b new-start def456

Here def456 is the commit hash of the last good state you want to revert to. This creates a new branch new-start starting from def456.

3. Using git reset

If you want to completely undo a series of commits without preserving the reversion traces in history, you can use the git reset command:

shell
git reset --hard <commit-hash>

Example:

Assume the last good commit hash is def456, and you want to undo all commits after it:

shell
git reset --hard def456

This will reset the current branch's HEAD to def456, and all commits after it will be deleted. This operation is irreversible, so ensure this is what you want.

In all cases, if you have already pushed these commits to a remote repository and others may have worked based on these commits, proceed with caution. If you indeed need to perform such operations on the remote repository, you may need to execute git push --force to overwrite the history of the remote branch, which can affect other collaborators. Before performing these operations, ensure you fully understand the meaning and potential impacts of each command, and it's best to do this after backing up the current repository.

2024年6月29日 12:07 回复

你的答案