>_ IzzyLab

Hands-on task

This task is step 16 of the course “Git: rewriting and rescuing history”

Rescue a commit from detached HEAD

medium~5 min

In /root/repo someone did a git checkout onto an old commit (the repository is currently in a "detached HEAD" state), did some work there in a new commit with an important file rescue.txt (contents IMPORTANT) — and this commit isn't attached to any branch: switch to main and it will be lost. Without losing it, save the current commit into a new branch named rescue so that rescue.txt survives.

What you'll practise:
  • detached HEAD
  • git branch
  • git switch
  • git reflog
  • commit references

Topic breakdown

"Detached HEAD" is the state where HEAD points directly at a commit rather than at a branch. Such a commit is held by nothing: switch to a branch and it becomes unreachable and sooner or later falls to garbage collection. The rescue is to attach a branch reference to it while you're standing on it (git branch creates a branch on the current commit, git switch -c creates and switches to it right away). Even if the commit is already "lost", its hash is still visible in git reflog, and a branch can be created at it by hash.

What's checked

  1. the rescue branch exists
  2. rescue.txt saved in the branch

What it looks like