2

I am new to Git and I think I don't know what I am doing.

I was editing a bunch of files including new ones. Since there were lots of changes, I wanted to commit and push them before losing my work.

So I used:

git add .
git commit -m "Blablabla"

With the following answer:

[detached HEAD b5c9786] Blablabla
 29 files changed, 794 insertions(+), 265 deletions(-)

Then:

git push

With the answer

fatal: You are not currently on a branch.
To push the history leading to the current (detached HEAD)
state now, use

    git push origin HEAD:<name-of-remote-branch>

I realized that I forgot to go back to the feature branch last time I did a pull, so I switched to the feature branch.

git branch feature

Which obviously loaded the state when it was after last push.

Before I panic and do something stupid, my last commit should be somewhere locally in the .git folder right?

I have the following files:

COMMIT_EDITMSG
HEAD
config
hooks
info
objects
refs
FETCH_HEAD
ORIG_HEAD
description
index
logs
packed-refs

COMMIT_EDITMSG and HEAD have timestamp around my last commit.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • Hahaha!!! I liked your post. Everything is available in Git local changes. Best part with git is you never lose anything. – Kunal Vohra Jun 25 '20 at 05:04
  • 1
    Does this answer your question? [What to do with commit made in a detached head](https://stackoverflow.com/questions/7124486/what-to-do-with-commit-made-in-a-detached-head) Look at [this](https://stackoverflow.com/a/33270008/3135317) response in particular. – FoggyDay Jun 25 '20 at 05:05
  • Thanks for the reply. I already left the detached branch and I don't know how to get back to that detached branch. If I do bit branch I only have master and feature, not the detached. –  Jun 25 '20 at 05:20
  • As an aside, "There were lots of changes, I wanted to commit and push them before losing my work" isn't really what Git is for (although it can be valid for some use cases). You're essentially using Git as a backup solution whereas what is excels at is version control. Your commits should aim to be atomic, meaning you commit every time you make a single "unit" of change. So e.g. if you modify two unrelated functions, they should each appear in their own commit. In this way you can tell which commit changed what, and easily restore any version of any "unit" when you want to. – JBentley Jun 25 '20 at 17:00

1 Answers1

4

I already left the detached branch and I don't know how to get back to that detached branch

That is where git reflog comes in.

If you had committed before leaving the detached HEAD, you will find your commit listed in the reflog.
You can then git cherry-pick it, and apply it on your current branch.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Thanks much, exactly what I needed! I didn't know about reflog, that's very handy! –  Jun 25 '20 at 05:38