Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I wish I'd branched in Git - can I turn back time?

Tags:

git

This is a use case which has come up a couple of times. Because I'm (unfortunately) not in the habit of branching for every feature, sometimes I start work on a task, make a couple of commits, and then say "Crap...this is more complicated than I thought...I wish I'd created a branch three commits ago."

At that point, I can go back to a particular commit and branch from there, but that leaves those new commits on the master, and not on the feature branch. I could cherry-pick each commit, or maybe rebase it onto the new branch somehow, but that still leaves the branch commits on the master.

How can I make this happen?

like image 289
Chris B. Behrens Avatar asked May 10 '17 18:05

Chris B. Behrens


People also ask

How do I change my head to the latest commit?

To hard reset files to HEAD on Git, use the “git reset” command with the “–hard” option and specify the HEAD. The purpose of the “git reset” command is to move the current HEAD to the commit specified (in this case, the HEAD itself, one commit before HEAD and so on).

Does git checkout change working directory?

Git Checkout File Checking out a file is similar to using git reset with a file path, except it updates the working directory instead of the stage. Unlike the commit-level version of this command, this does not move the HEAD reference, which means that you won't switch branches.

What does git checkout HEAD do?

Remember that the HEAD is Git's way of referring to the current snapshot. Internally, the git checkout command simply updates the HEAD to point to either the specified branch or commit. When it points to a branch, Git doesn't complain, but when you check out a commit, it switches into a “detached HEAD” state.


1 Answers

Shortest thing to do:

  • create new branch where master is
  • reset master back to where you want it:

Suppose you are on master and you realize the last two commits on master should be on a feature branch:

git branch feature-A
git reset --hard HEAD~2

That's it.

like image 168
eftshift0 Avatar answered Oct 27 '22 21:10

eftshift0