How can I move HEAD back to a previous location? (Detached head) & Undo commits
Asked Answered
P

8

324

In Git, I was trying to do a squash commit by merging in another branch and then resetting HEAD to the previous place via:

git reset origin/master

But I need to step out of this. How can I move HEAD back to the previous location?

I have the SHA-1 fragment (23b6772) of the commit that I need to move it to. How can I get back to this commit?

Pammie answered 29/12, 2015 at 21:53 Comment(3)
HEAD is just a pointer to your current location (or revision to be precise). git checkout 23b6772 should do.Goodard
Possible duplicate of Revert Git repo to a previous commitAtal
@YaroslavAdmin No it should not. Checking out a commit directly is the reason detached HEAD state happened (since remote-tracking branches can't be checked out themselves and automatically defer to the commit they point to when you try to do so like OP did) Also, sorry for the necromantic comment :-) I sort of hope the initial problem is solved already...Papal
B
698

Before answering, let's add some background, explaining what this HEAD is.

First of all what is HEAD?

HEAD is simply a reference to the current commit (latest) on the current branch.
There can only be a single HEAD at any given time (excluding git worktree).

The content of HEAD is stored inside .git/HEAD and it contains the 40 bytes SHA-1 of the current commit.


detached HEAD

If you are not on the latest commit - meaning that HEAD is pointing to a prior commit in history it's called detached HEAD.

Enter image description here

On the command line, it will look like this - SHA-1 instead of the branch name since the HEAD is not pointing to the tip of the current branch:

Enter image description here

Enter image description here


A few options on how to recover from a detached HEAD:


git checkout

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits to go back

This will checkout the new branch pointing to the desired commit.
This command will checkout to a given commit.
At this point, you can create a branch and start to work from this point on.

# Checkout a given commit.
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# Create a new branch forked to the given commit
git checkout -b <branch name>

git reflog

You can always use the reflog as well.
git reflog will display any change which updated the HEAD and checking out the desired reflog entry will set the HEAD back to this commit.

Every time the HEAD is modified there will be a new entry in the reflog

git reflog
git checkout HEAD@{...}

This will get you back to your desired commit

Enter image description here


git reset --hard <commit_id>

"Move" your HEAD back to the desired commit.

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.
  • Note: (Since Git 2.7) you can also use the git rebase --no-autostash as well.

enter image description here


git revert <sha-1>

"Undo" the given commit or commit range.
The revert command will "undo" any changes made in the given commit.
A new commit with the undo patch will be committed while the original commit will remain in history as well.

# Add a new commit with the undo of the original one.
# The <sha-1> can be any commit(s) or commit range
git revert <sha-1>

This schema illustrates which command does what.
As you can see there, reset && checkout modify the HEAD.

Enter image description here

Bobbyebobbysocks answered 29/12, 2015 at 21:56 Comment(4)
If you are not on the latest commit - meaning that HEAD is pointing to a prior commit in history its called detached HEAD unless that prior commit in history is the tip of a different branch. In my experience, you could say that you are detached if HEAD is not pointing to a commit that is also pointed to by any branch. This does not apply for tags.Joses
You can be in detached HEAD and on the same time have a branch with the same commit as the HEAD of this branch. I dont understand your commentBobbyebobbysocks
git reset <commit> from a detached head did not work for me. That's what I tried: I created an empty repo, added a file and committed 4 changes to it in order to create the master branch as seen in your top picture. Then I switched to commit #2 in order to get into "detached head" state. Then I issued git reset [--hard | --soft] <commit #3>. Now HEAD points to commit #3 and master (.git/refs/heads/master) still points to the tip of the branch (== commit #4). In other words, I'm still in "detached head" state. Why is this?Narcotic
If you wish you can move to chat and i can try to resolve it with youBobbyebobbysocks
B
69

First reset locally:

git reset 23b6772

To see if you're on the right position, verify with:

git status

You will see something like:

On branch master Your branch is behind 'origin/master' by 17 commits, and can be fast-forwarded.

Then rewrite history on your remote tracking branch to reflect the change:

git push --force-with-lease // a useful command @oktober mentions in comments

Using --force-with-lease instead of --force will raise an error if others have meanwhile committed to the remote branch, in which case you should fetch first. More info in this article.

Beckiebeckley answered 10/10, 2018 at 13:14 Comment(3)
Be EXCEEDINGLY CAUTIOUS with git push --force. In many situations it will make you the least popular person on the team for a little while....Jejune
to add to the above note, I just came across this quote at about.gitlab.com/blog/2014/11/26/keeping-your-code-protected and had to add it: "A single git push --force command can easily ruin the day for a lot of people: [186 Jenkins] repositories have their branch heads rewinded to point to older commits, and in effect the newer commits were misplaced after the bad git-push." --very unpopular developer....Jejune
thank you! this helped me un-do a bad merge. since merges don't react the same way to revert as commits I found myself in an incredibly difficult situation. force-with-lease gave me the confidence to rewrite the git history of the branch without affecting other people's work. bravo!Sprig
J
26

Quickest possible solution (just 1 step)

Use git checkout -

You will see Switched to branch <branch_name>. Confirm it's the branch you want.


Brief explanation: this command will move HEAD back to its last position. See note on outcomes at the end of this answer.


Mnemonic: this approach is a lot like using cd - to return to your previously visited directory. Syntax and the applicable cases are a pretty good match (e.g. it's useful when you actually want HEAD to return to where it was).


More methodical solution (2-steps, but memorable)

The quick approach solves the OP's question. But what if your situation is slightly different: say you have restarted Bash then found yourself with HEAD detached. In that case, here are 2 simple, easily remembered steps.

1. Pick the branch you need

Use git branch -v

You see a list of existing local branches. Grab the branch name that suits your needs.

2. Move HEAD to it

Use git checkout <branch_name>

You will see Switched to branch <branch_name>. Success!


Outcomes

With either method, you can now continue adding and committing your work as before: your next changes will be tracked on <branch_name>.

Note that both git checkout - and git checkout <branch_name> will give additional instructions if you have committed changes while HEAD was detached.

Jejune answered 9/8, 2016 at 14:10 Comment(4)
This is not working because if I do (assuming that 8acc968 is HEAD~2) git checkout 8acc968then git branch -v has MyBranch in the list below ...but then git checkout MyBranch deletes my comments.Beckiebeckley
Hi @Beckiebeckley - git checkout 8acc968 will check out a commit, not a branch. If MyBranch has the commits you want, try git checkout MyBranch. If it does not contain the changes in commit 8acc968, you would need to merge those changes after checking out the branch.Jejune
Thanks for the answer! I did git checkout to see a previous commit and wanted to get back to the latest commit. But without the latest commit hash, I was pretty much lost. This solution is perfect for my situation!Curtilage
git checkout - does not necessarily have the effect you say.Otalgia
C
8

The question can be read as:

I was in detached-state with HEAD at 23b6772 and typed git reset origin/master (because I wanted to squash). Now I've changed my mind, how do I go back to HEAD being at 23b6772?

The straightforward answer being: git reset 23b6772

But I hit this question because I got sick of typing (copy & pasting) commit hashes or its abbreviation each time I wanted to reference the previous HEAD and was Googling to see if there were any kind of shorthand.

It turns out there is!

git reset - (or in my case git cherry-pick -)

Which incidentally was the same as cd - to return to the previous current directory in *nix! So hurrah, I learned two things with one stone.

Clamp answered 22/7, 2017 at 4:46 Comment(0)
M
1

When you run the command git checkout commit_id then HEAD detached from 13ca5593d(say commit-id) and branch will be on longer available.

Move back to previous location run the command step wise -

  1. git pull origin branch_name (say master)
  2. git checkout branch_name
  3. git pull origin branch_name

You will be back to the previous location with an updated commit from the remote repository.

Mulvey answered 18/1, 2019 at 9:15 Comment(0)
M
1

Today, I mistakenly checked out on a commit and started working on it, making some commits on a detach HEAD state. Then I pushed to the remote branch using the following command:

git push origin HEAD: <My-remote-branch>

Then

git checkout <My-remote-branch>

Then

git pull

I finally got my all changes in my branch that I made in detach HEAD.

Maltase answered 25/6, 2019 at 11:45 Comment(0)
L
1

This may not be a technical solution, but it works. (if anyone of your teammate has the same branch in local)

Let's assume your branch name as branch-xxx.

Steps to Solve:

  • Don't do update or pull - nothing
  • Just create a new branch (branch-yyy) from branch-xxx on his machine
  • That's all, all your existing changes will be in this new branch (branch-yyy). You can continue your work with this branch.

Note: Again, this is not a technical solution, but it will help for sure.

Letitialetizia answered 9/6, 2020 at 7:20 Comment(0)
P
0

Move last non-pushed commits to a new branch

If your problem is that you started committing on the WRONG_BRANCH, and want to move those last non-pushed commits to the RIGHT_BRANCH, the easiest thing to do is

  1. git checkout WRONG_BRANCH
  2. git branch RIGHT_BRANCH
  3. git reset —-hard LAST_PUSHED_COMMIT
  4. git checkout RIGHT_BRANCH

At this point, if you run git log HEAD you will see that all your commits are there, in the RIGHT_BRACH.

Data

  • WRONG_BRANCH is where your committed changes (yet to push) are now
  • RIGHT_BRANCH is where your committed changes (yet to push) will be
  • LAST_PUSHED_COMMIT is where you want to restore the WRONG_BRANCH to
Photomicrograph answered 20/5, 2021 at 15:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.