0

I reverted to an older commit in order to discard some changes that had been made from a certain point.

Then I made my changes on top of those, and ended up with a detached HEAD situation.

The commit history looks as follows:

enter image description here

In hindsight, I am not sure whether I did the right thing. (I think I just checked out the older commit and worked on top of that).

From here, all I want is to make my latest commit the new master. I don't care about keeping the other commits.

What is the easiest way to make my new commit the master and update it like that remotely? (I'm not sharing the repository with anyone else, so no-one else is impacted).

mydoghasworms
  • 18,233
  • 11
  • 61
  • 95
  • Create a branch from the detached head, delete the existing master then rename the current branch to master – Paolo Apr 06 '23 at 10:30

2 Answers2

1
  1. Create a (new) branch from your current commit (deleting the branch first if it exists): git checkout -B master
  2. Force push to the remote (this will lose your commits and change the history on the server): git push origin +master
knittl
  • 246,190
  • 53
  • 318
  • 364
0

Quickly;

$ git show             # shows the current HEAD. Copy the commit hash.
$ git checkout master  # switch to master..
$ git reset --hard <commit hash>  # sets the current branch (now master) to the specified commit hash.
### CAUTION ###
$ git push -f @{u}     # force-push master to its remote tracking branch (USE WITH CAUTION!!)

Note: the @{u} is shorthand for the upstream tracking branch. I personally found it to work in bash but not in zsh. To be safe, you can explicitly name the refs (assuming your remote is origin), like so:

git push -f origin master:master

In any case, git reflog can display the local HEAD's recent history, so should come in handy when trying to undo mistakes (e.g. leaving a detached-head, an "oh-no, I lost my work" type scenario), or to investigate where a "mistake" has been made (e.g. checking out a commit as a detached head, an "oh-no, I lost track of work" type scenario).

micromoses
  • 6,747
  • 2
  • 20
  • 29