📅  最后修改于: 2023-12-03 14:41:27.565000             🧑  作者: Mango
Sometimes, you might have made multiple changes and committed them in a single commit. But later on, you realized that one or more of those changes were not needed, and you want to revert only that particular change in git. In this guide, we will show you how to revert only part of a commit using Shell/Bash commands.
First, you need to identify the commit you want to revert. You can do this by either checking the commit messages or using the git log command.
git log
This will list all the commits in reverse chronological order. Identify the commit hash you want to revert.
Create a new branch to revert the changes. This will enable you to revert the changes without affecting any other branch.
git checkout -b <new_branch_name> <commit_hash>
Replace <new_branch_name>
with the name of the new branch, and <commit_hash>
with the commit hash you want to revert.
Now, you need to identify the changes you want to revert. You can do this by using the git diff command.
git diff <commit_hash> [<file_path>...]
Replace <commit_hash>
with the commit hash you want to revert and <file_path>...
with the path of the file you want to revert.
Once you have identified the changes you want to revert, use the git checkout command to revert only those changes.
git checkout <commit_hash> -- <file_path>
Replace <commit_hash>
with the commit hash you want to revert, and <file_path>
with the path of the file you want to revert.
Once you have reverted the changes, you need to commit the changes to the new branch.
git commit -m "Reverted only selected changes from <commit_hash>"
Replace <commit_hash>
with the commit hash you want to revert.
Now, you need to merge the changes to the original branch.
git checkout <original_branch>
git merge <new_branch_name>
Replace <original_branch>
with the name of the original branch and <new_branch_name>
with the name of the new branch.
Finally, push the changes to the remote repository.
git push <remote_name> <original_branch>
Replace <remote_name>
with the name of the remote repository and <original_branch>
with the name of the original branch.
In this guide, we have shown you how to revert only part of a commit using Shell/Bash commands. This can be a useful tool when you need to revert changes without affecting the rest of the commit history.