tanookiben tanookiben - 1 year ago 91
Git Question

Can I delete a git commit but keep the changes

In one of my development branches, I made some changes to my codebase. Before I was able to complete the features I was working on, I had to switch my current branch to master to demo some features. But just using a "git checkout master" preserved the changes I also made in my development branch, thus breaking some of the functionality in master. So what I did was commit the changes on my development branch with a commit message "temporary commit" and then checkout master for the demo.

Now that I'm done with the demo and back to work on my development branch, I would like to remove the "temporary commit" that I made while still preserving the changes I made. Is that possible?

Answer Source

It's as simple as this:

git reset HEAD^

git reset without a --hard or --soft moves your HEAD to point to the specified commit, without changing any files. HEAD^ refers to the (first) parent commit of your current commit, which in your case is the commit before the temporary one.

Note that another option is to carry on as normal, and then at the next commit point instead run:

git commit --amend [-m … etc]

which will instead edit the most recent commit, having the same effect as above.

Note that this (as with nearly every git answer) can cause problems if you've already pushed the bad commit to a place where someone else may have pulled it from. Try to avoid that