How to Delete a Commit but Preserve Changes in Git
- Delete a Commit but Preserve Changes in Git
-
Delete a Commit and Keep Changes With the
git reset
Command
This article outlines the steps necessary to undo a Git commit while preserving the changes introduced by the same commit. We will cover two commands we can use that will have the same effects.
Without further ado, let’s jump right in.
Delete a Commit but Preserve Changes in Git
Let’s use an example to explore this concept.
Assuming we have the commit history shown below in our repo, how do we delete the latest commit but keep the changes?
There are two methods we can employ to achieve our goal. Let’s check out the first method, which is the easiest.
Delete a Commit and Keep Changes With the git reset
Command
We can utilize the git reset
command to undo a commit while preserving the changes, as shown below:
$ git reset HEAD~
This should remove the Update Config.py
commit but keep the changes to the file. We can run the git log
command to confirm our case.
If you run the git status
command, you will see that you have unstaged changes. This does not necessarily mean that your file has changed.
When we use the git reset
command without a --soft
or --hard
option, Git will undo the specified commit without changing the files affected by the commit.
You can add the changes to the index and run the git commit --amend--no-edit
command to remove the changes from the index and mount them to the latest commit.
Alternatively, instead of deleting the commit, you can carry on with development and run the git commit --amend
command when it is time to make a new commit. At this point, you will add your new modifications to the commit you want to delete, and you can also edit the commit message.
In a nutshell, Git allows us to undo a commit and keep the changes introduced by the same commit. We can use the git reset
command and the git commit --amend
command to achieve our goal.
John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.
LinkedIn