3

If I have a local branch in git with commits A, B, C, D, E and I choose to delete it using

git branch -D myBranch

but I save the commit IDs before deleting, will I be able to cherry-pick some of these commits to another branch by their IDs afterwards?

isherwood
  • 58,414
  • 16
  • 114
  • 157
  • 3
    Yes, until [the reflogs expire](https://git-scm.com/docs/git-reflog) and [the garbage collection](https://git-scm.com/docs/git-gc) throws them away, which will take a while (30 or 90 days by default). But if you plan to cherry-pick then just ... don't delete the branch yet? What's wrong with keeping it around until you've cherry-picked everything you want off it? – Joachim Sauer Feb 01 '23 at 15:49
  • 1
    Why not try it out? It's just 5 or so git commands... less typing than asking a question here and you will know for sure. – Friedrich Feb 01 '23 at 15:54
  • The problem was actually, that I am working together with another person on one and the same branch (I know, it is not a good practice ...). And I faced a case when I my local branch dramatically diverged from remote: I had some local commits which I had not pushed yet while the other person pushed some commits, including merge commits (!). So in the end I found it easier just to delete the local branch and to check it out again and to cherry-pick my new commits onto the top. I tried git pull --rebase=true but it looked like it tried to add many commits to my branch because of the merge commit – user16038501 Feb 01 '23 at 16:12
  • In the end, it worked out fine, thanks! – user16038501 Feb 01 '23 at 16:13
  • @user16038501: what I would have done in such a situation would be to rename my local (shared) branch to something like `old-shared-branch`, then create a new branch, cherry pick from `old-shared-branch` and when I had all I needed, just delete `old-shared-branch`. This way you don't need to depend on the semi-magical property of picking by hash commits that are no longer reachable via any references. – Joachim Sauer Feb 02 '23 at 11:03

1 Answers1

2

Yes. Just specify the commit ids (SHAs) in the cherry-pick command:

git cherry-pick -x <commit-hash>

(The -x is not required, but recommended as it will give you a standard comment.) This answer has more details.

Mark Meuer
  • 7,200
  • 6
  • 43
  • 64
  • 1
    Correct. But `-x` is intended for the case where you have to cherry-pick a commit from some other part of the history that is there to stay. In this case, however, the referenced commit will be clean away and be no longer available. It does not help to have a reference to a commit that does not exist anymore. – j6t Feb 01 '23 at 19:50