Git: Checkout a Single File from a Previous Commit

Often we alter or delete a file that we didn’t really want to. Sometimes this goes unnoticed for a few commits. It’s fairly easy in git to retrieve a specific file from a specific commit.

git checkout <commit> <path>
git checkout f08b32 ./src/main.c
git checkout HEAD~2 ./src/main.c

How to reattach a GIT detached head.

$ git status
HEAD detached at 36bc359
nothing to commit, working tree clean

$ git branch fix-detached
$ git checkout main
$ git merge fix-detached -Xtheirs
$ git branch -d fix-detached