Git went back 5 commits and forgot to create a new branch, how to come back?

git, git-branch, git-checkout, git-commit

Solution

If your description of the commands you ran is correct - create a branch now on what you've been working on to create a reliable named reference to it (`git branch WIP HEAD`). Then rebase against master (`git rebase master`) and checkout master and merge in WIP.

You can test this out fairly simply to replicate the situation and explore the commands you need and what they do. For this `git graph` is aliased to `git log --graph --oneline --decorate --abbrev-commit` and just produces a pretty git log.

Create a demo repository with 8 commits then checkout six back and create some more commits

$ cd /tmp && git init demo && cd demo
$ for msg in one two three four five six seven eight; do echo $msg>file && git add file && git commit -m $msg; done
$ git checkout HEAD~6
$ for msg in nine ten eleven; do echo $msg>file && git add file && git commit -m $msg; done

So lets just look at this:

$ git graph --all
* e81b31c (HEAD) eleven
* c005e75 ten
* c567d25 nine
| * 4d28c3d (master) eight
| * 380f715 seven
| * 9966c80 six
| * 6b2f757 five
| * e43d079 four
| * ce0ff34 three
|/
* 8d5a6e1 two
* 1f880ae one

So really this just looks like a feature branch taken from 8d5a6e1. The only special thing is its only reference is HEAD. If you now add a branch reference it will become a normal feature branch.

If you accidentally checkout master or some other branch before you labelled this working branch with a branch tag then you would loose the reference to the top of this new chain of commits. Now you lost the branch. In this case you need to use the reflog to find the last commit on that chain and add a branch reference to that commit. We can see this from the demo repository above:

$ git reflog
e81b31c HEAD@{0}: commit: eleven
c005e75 HEAD@{1}: commit: ten
c567d25 HEAD@{2}: commit: nine
8d5a6e1 HEAD@{3}: checkout: moving from master to HEAD~6
4d28c3d HEAD@{4}: reset: moving to 4d28c3d
....

We can see from the reflog that a few commits back, we checked out HEAD~6 and then added three more commits. We could then issue `git branch recover-commits e81b31c` to get a branch that points to that set of commits and recover them.

Problem

I had to go back six commits in Git with the command ``` git checkout idofthecommit ``` What I have been doing was continuing commit, commit, commit. Since I have created no real new branch, when I git push to external repositories with ``` git push origin master ``` it tells me that everything is up-to-date. This means I haven't actually made any changes in the master. How I can move the commits I have been doing to the master branch?

Original source