To undo the last Git commit, you can use the git reset
command. Here’s how to do it:
- Make sure you are on the branch where you want to undo the commit. You can use the
git branch
command to check the current branch, andgit checkout
to switch to a different branch if needed. - Run the
git log
command to view the commit history and identify the hash of the commit you want to undo. Note the first 7 characters of the commit hash. - Run the
git reset
command with the--soft
option followed by the hash of the commit you want to undo. This will reset the branch to the specified commit, but keep the changes from that commit staged.
git reset --soft HEAD~1 //Alternatively, you can use the shorthand HEAD instead of HEAD~1 to refer to the last commit.
- Run the
git status
command to verify that the changes from the undone commit are now staged. - Run the
git commit
command to create a new commit with the changes from the undone commit staged. This will open your default text editor for you to write the commit message. - Save and close the commit message file to create the new commit.
- Finally, run the
git push
command to push the changes to the remote repository.
git push
Note that undoing a commit using git reset
will remove the changes made in that commit, so use it with caution. It’s a good practice to make a backup or create a new branch before running any potentially destructive command.