Jeremy Iglehart
Jeremy Iglehart

Reputation: 4479

How to get back to a git branch after a git revert

So, I ended up having to change the whole directory tree of my project because of a fundamental problem with my code - or so I thought. So I made a commit before the big changes, then I realized after making the changes that I did not need to. So I performed

git checkout ##SHA##

I was able to make the whole project working the way it should, but now I have a different problem. I am no longer checked-out in the branch I was working in. How do I keep the code I have now and get back to working within the branch?

git branch -a

says that I am in

* (no branch)

Anyone know what I can do without just making a new branch and deleting the old one?

Upvotes: 3

Views: 1114

Answers (4)

Carl
Carl

Reputation: 44448

  1. Create a branch: git branch -b branch_for_new_code
  2. Add and commit your changes.
  3. Checkout the branch you want to get back to: git checkout branch_i_was_on
  4. Merge the new branch with the old: git merge branch_for_new_code
  5. Delete the new branch once it has been merged.

For the future, remember a simple rule of thumb: When you're doing something you're not sure about, make a branch first. Finally, only checkout branch names unless you really know what you are doing.

Upvotes: 1

manojlds
manojlds

Reputation: 301147

Never do git checkout <hash>. It is meant to temporarily examine a commit (and hence the no branch that you see). What you wanted to do was, while in the branch, git reset --hard <hash> ( remove the --hard if you have changes you need in the working directory.)

To recover:

git checkout the_branch
git reset --hard <hash>

Note that the <hash> above is going to be the same one that you used with git checkout while trying to "revert" the changes.

Upvotes: 6

Greg Hewgill
Greg Hewgill

Reputation: 993095

If you're sure that you are where you want the branch to be, you can:

git branch -D my_branch
git checkout -b my_branch

This deletes the old branch pointer, and creates a new one pointing to your current HEAD.

Upvotes: 0

dorsh
dorsh

Reputation: 24710

Checkout back to your branch, then merge the changes you made on the headless branch:

git checkout my_branch
git merge ##SHA##

You should then have branch my_branch at the latest commit you've made.

Upvotes: 2

Related Questions