Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Committing to master with detached HEAD

Tags:

git

github

I was up coding late last night and made a fatal mistake. I was on a branch and ran git checkout on an older commit. I then started writing on top of that code. What are the steps needed to push to git master?

To be clear: I want to push the repo I have locally saved on my computer to the master origin.

Thank you!

like image 855
Chris Jones Avatar asked Dec 19 '25 13:12

Chris Jones


2 Answers

Assuming the detached HEAD is where you want master to be (i.e. you don't have any commits in master that you want to keep nor you have any modified files in your working directory) you can move the master branch to point to the commit referenced by HEAD by using the --force option of git branch.

From the documentation:

-f
--force
Reset <branchname> to <startpoint> if <branchname> exists already. Without -f git branch refuses to change an existing branch.

In your case, you would simply say:

git branch -f master HEAD

Then you can checkout master and push the commits to the remote master branch like you usually would:

git checkout master
git push origin master

Again, as @torek pointed out in the comments, this solution assumes that you want to reset the master branch to the commit referenced by HEAD and don't care about whatever commits are currently reachable from master.

like image 54
Enrico Campidoglio Avatar answered Dec 21 '25 04:12

Enrico Campidoglio


Stash your changes, switch back to master and apply changes there, and continue your work there:

git stash save
git checkout master
git stash pop

After that you can do git add and git commit when needed, it'll be on top of the master branch.

like image 31
yelsayed Avatar answered Dec 21 '25 04:12

yelsayed