ChatGPT解决这个技术问题 Extra ChatGPT

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?

Next time: git stash
@MattBall, not necessarily. While git stash is a good tool, "work in progress" throw-away commits are quite a legitimate device, too.
This is a great resource strait from Github: How to undo (almost) anything with Git
@MattBall @kostix Yeah, stash is particularly ill-suited for "long-term" stashing, given that it's one global stack for the whole repo. I want to be able to stash changes on a branch and then go to other branches, do whatever else, come back days later without worrying that I might have used git stash on some other branch in the interim.
One thing worth noting about stash is that it is completely local and will be prone to code loss from repo-deletion or recreation or, hardware failure or loss. IMO, it really should be used only for very short term WIP. Love a WIP commit before going on holiday :P .. call it a brain dump commit!

S
Svish

It's as simple as this:

git reset HEAD^

Note: some shells treat ^ as a special character (for example some Windows shells or ZSH with globbing enabled), so you may have to quote "HEAD^" or use HEAD~1 in those cases.

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


This is by far the simplest, but if you've already pushed your commit to a remote and someone else pulled it, I'd be very hesitant to do anything except apologize.
I get More? after doing this. Whatever I type in at that prompt gives me fatal: ambiguous argument 'HEADwhateverItypedIn': unknown revision or path not in the working tree.
@DaAwesomeP sounds like you're using a shell which treats ^ as a special character. You could either quote the reference "HEAD^", or use the alternative syntax HEAD~1 unquoted
Worked for me, had to escape character though git reset HEAD\^
@kostix FWIW that link has changed to git-scm.com/book/en/v2/Git-Tools-Reset-Demystified
S
Steven

There are two ways of handling this. Which is easier depends on your situation

Reset

If the commit you want to get rid of was the last commit, and you have not done any additional work you can simply use git-reset

git reset HEAD^

Takes your branch back to the commit just before your current HEAD. However, it doesn't actually change the files in your working tree. As a result, the changes that were in that commit show up as modified - its like an 'uncommit' command. In fact, I have an alias to do just that.

git config --global alias.uncommit 'reset HEAD^'

Then you can just used git uncommit in the future to back up one commit.

Squashing

Squashing a commit means combining two or more commits into one. I do this quite often. In your case you have a half done feature commited, and then you would finish it off and commit again with the proper, permanent commit message.

git rebase -i <ref>

I say above because I want to make it clear this could be any number of commits back. Run git log and find the commit you want to get rid of, copy its SHA1 and use it in place of <ref>. Git will take you into interactive rebase mode. It will show all the commits between your current state and whatever you put in place of <ref>. So if <ref> is 10 commits ago, it will show you all 10 commits.

In front of each commit, it will have the word pick. Find the commit you want to get rid of and change it from pick to fixup or squash. Using fixup simply discards that commits message and merges the changes into its immediate predecessor in the list. The squash keyword does the same thing, but allows you to edit the commit message of the newly combined commit.

Note that the commits will be re-committed in the order they show up on the list when you exit the editor. So if you made a temporary commit, then did other work on the same branch, and completed the feature in a later commit, then using rebase would allow you to re-sort the commits and squash them.

WARNING:

Rebasing modifies history - DONT do this to any commits you have already shared with other developers.

Stashing

In the future, to avoid this problem consider using git stash to temporarily store uncommitted work.

git stash save 'some message'

This will store your current changes off to the side in your stash list. Above is the most explicit version of the stash command, allowing for a comment to describe what you are stashing. You can also simply run git stash and nothing else, but no message will be stored.

You can browse your stash list with...

git stash list

This will show you all your stashes, what branches they were done on, and the message and at the beginning of each line, and identifier for that stash which looks like this stash@{#} where # is its position in the array of stashes.

To restore a stash (which can be done on any branch, regardless of where the stash was originally created) you simply run...

git stash apply stash@{#}

Again, there # is the position in the array of stashes. If the stash you want to restore is in the 0 position - that is, if it was the most recent stash. Then you can just run the command without specifying the stash position, git will assume you mean the last one: git stash apply.

So, for example, if I find myself working on the wrong branch - I may run the following sequence of commands.

git stash
git checkout <correct_branch>
git stash apply

In your case you moved around branches a bit more, but the same idea still applies.

Hope this helps.


git config --global alias.uncommit reset HEAD^ just aliases uncommit to reset. Instead, do git config --global alias.uncommit 'reset HEAD^'
Note that you will have to use ^^ instead of ^ if using in a windows command prompt.
m
myselfmiqdad

I think you are looking for this

git reset --soft HEAD~1

It undoes the most recent commit whilst keeping the changes made in that commit to staging.


Thanks. This worked for me. Calling git reset HEAD^ on Windows just prompts "More?" - whatever that means
@Tyron ^ is an escape character in DOS. When paired with a new line, it serves as a continuation prompt for the preceding command. Typing git reset HEAD^^ should work on Windows.
v
vallentin

Yes, you can delete your commit without deleting the changes:

git reset @~

Interesting, compact syntax, I haven't seenor used it before. How is that different from git reset --soft or git reset --keep?
it didn't work with me with I do: git reset @~ commit_hash the commit stays as is and never deleted
B
Bar Horing Amir

You're looking for either git reset HEAD^ --soft or git reset HEAD^ --mixed.

There are 3 modes to the reset command as stated in the docs:

git reset HEAD^ --soft

undo the git commit. Changes still exist in the working tree(the project folder) + the index (--cached)

git reset HEAD^ --mixed

undo git commit + git add. Changes still exist in the working tree

git reset HEAD^ --hard

Like you never made these changes to the codebase. Changes are gone from the working tree.


The best answer with all main details.
X
Xys

2020 Simple way :

git reset <commit_hash>

(The commit hash of the last commit you want to keep).

If the commit was pushed, you can then do :

git push -f

You will keep the now uncommitted changes locally


When you say this is the '2020 Simple way' is that implying this method wasn't possible in previous versions? If so which version of Git is required to use this method?
W
Wim Feijen

In my case, I already pushed to the repo. Ouch!

You can revert a specific commit while keeping the changes in your local files by doing:

git revert -n <sha>

This way I was able to keep the changes which I needed and undid a commit which had already been pushed.


In my case, I needed to revert something i already pushed to the remote repository. Even more ouch! Best way was to git revert bad-commit-sha, then git revert -n revert-commit-just-created-sha and then repair from there. You got me halfway. Thanks!
This seems to do the opposite, no? It creates new changes which correspond to a revert of the changes done in the selected commit. If you were to commit these new changes, you will have undone the work you wanted actually to keep.
Hence the -n option, which leaves the changes that the reversion would do staged but not committed. Then you can pick and choose which of those reversion changes to keep or discard
C
Community

For those using zsh, you'll have to use the following:

git reset --soft HEAD\^

Explained here: https://github.com/robbyrussell/oh-my-zsh/issues/449

In case the URL becomes dead, the important part is:

Escape the ^ in your command You can alternatively can use HEAD~ so that you don't have to escape it each time.


I can never remember this command and have to google this and find my own answer hahahaha
git reset HEAD^ is working in zsh for me, may have been fixed.
@BenKolyaMansley What version of zsh are you running?
I'm using zsh 5.3 (x86_64-apple-darwin18.0)
Hey everyone, me again, I've looked this up to many times I ended up throwing it in my .zshrc, which many may benefit from doing. Example: github.com/GregHilston/toolbox/blob/master/dot/zshrc#L147
n
nkharche

Using git 2.9 (precisely 2.9.2.windows.1) git reset HEAD^ prompts for more; not sure what is expected input here. Please refer below screenshot

https://i.stack.imgur.com/BfNIt.png

Found other solution git reset HEAD~#numberOfCommits using which we can choose to select number of local commits you want to reset by keeping your changes intact. Hence, we get an opportunity to throw away all local commits as well as limited number of local commits.

https://i.stack.imgur.com/m27db.png

https://i.stack.imgur.com/HvasB.png


You probably need to escape the ^ character - try git reset "HEAD^" or git reset HEAD\^
Adding to this, a git reset HEAD^^ works as a single ^ is treated as a new line.
R
Ruslan Osipov

One more way to do it.

Add commit on the top of temporary commit and then do:

git rebase -i

To merge two commits into one (command will open text file with explicit instructions, edit it).


Technically correct but nowhere near as elegant as simply doing git reset HEAD^. Git rebase has lots of room for error here.
L
Louis Caron

In some case, I want only to undo the changes on specific files on the first commit to add them to a second commit and have a cleaner git log.

In this case, what I do is the following:

git checkout HEAD~1 <path_to_file_to_put_in_different_commit>
git add -u
git commit --amend --no-edit
git checkout HEAD@{1} <path_to_file_to_put_in_different_commit>
git commit -m "This is the new commit"

Of course, this works well even in the middle of a rebase -i with an edit option on the commit to split.


W
Waaheeda

First you can see log with following command -

git reflog

this shows all commits, then find out your commit that you want to undo and the Head number associated it with and then enter following command

git reset HEAD@{#NumberOfCommitYouWantToUndo} 

e.g. git reset HEAD@{3}

git reset HEAD@{#} shows all Unstaged changes after reset