12

I have some garbage commits in my git repositry. These have been created by e.g. the git gui when changing the latest commit again and accidently creating additional commits.

Now I have some commits lying around with no HEAD assigned (detached, not part of any branch).

As I want to tidy up, my question is: How can I delete these commits (see F, G and H)? Is this done using rebase or revert or reset? Or using another tool? On which commit do I have to sit to do it?

A -- B -- C -- D -- E [master]
      \-- F -- G
           \-- H

Thanks

Christian

Christian Wolf
  • 1,187
  • 1
  • 12
  • 33
  • possible duplicate of [Listing and deleting Git commits that are under no branch (dangling?)](http://stackoverflow.com/questions/3765234/listing-and-deleting-git-commits-that-are-under-no-branch-dangling) – hunse Dec 02 '13 at 17:00

3 Answers3

16

Try this:

git reflog expire --expire=now
git gc --prune=now
cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • That did not change anything. Sorry – Christian Wolf Aug 07 '11 at 19:42
  • 1
    @Christian Wolf: If that didn't change anything, then your commits F, G, and H are referred to by *something*. Perhaps you've got a tag pointing at them? Or a stash? We don't know. – Greg Hewgill Aug 07 '11 at 19:52
  • @Christian: Have you verified using `git fsck --unreachable` that these commits are in fact dangling? If not, then no amount of gc/prune will remove them. You need to remove the reference(s) to them first. – cdhowie Aug 07 '11 at 20:26
  • I have to be been to tired yesterday. Today after sleeping and actualizing the commits do no more exist. – Christian Wolf Aug 08 '11 at 05:53
  • 1
    I was using gitk and thought I had the same issue, they weren't actually getting pruned. Try reload (shift-f5) vs update(f5). – Kurt Oct 04 '13 at 13:56
  • 11
    I had to use the `--all` flag with `reflog` to prune my commits: `git reflog expire --expire=now --all`. Also, I found the `git fsck` command useful for finding out what was going on; specifically, `git fsck --unreachable --no-reflog` shows commits that are unreachable or only reachable from the reflog. – hunse Dec 02 '13 at 17:03
  • 1
    I had to use `git gc --prune=now --aggressive` – Nick Grealy Feb 07 '17 at 05:09
6

Do the below:

git config gc.reflogexpireUnreachable now
git gc --prune=now
git config --unset gc.reflogexpireUnreachable
dieresys
  • 1,881
  • 1
  • 12
  • 8
manojlds
  • 290,304
  • 63
  • 469
  • 417
2
git reflog expire --expire=now --all
git gc --prune=now

Note: I know this is written in the comments of the most voted answer, but I keep finding myself coming back to this question and not immediately finding the answer that works. The --all option is the only thing that is missing from the most voted answer, but is what makes it work for me.

Jorge Galvão
  • 1,729
  • 1
  • 15
  • 28