Git & GitHub · 10 min · 120 XP
Wrong branch and detached HEAD
Move a commit made on the wrong branch, and keep work done in detached HEAD.
The most common slip: you meant to start a branch, forgot, and committed straight onto main. If you haven't pushed, it's a quick fix. A branch is just a label, so first create one where you are now (your commits come with it), then move main back to where the remote has it. Stash any uncommitted edits first, because reset --hard discards them.
git switch -c feature/discount # a new label at your commit, and you're on it git switch main git reset --hard origin/main # main goes back to what GitHub has
If the branch you meant already exists, copy the commit over with git cherry-pick. It replays one commit onto the branch you're on, as a new commit with a new ID. Then take it off main the same way.
git switch feature/discount git cherry-pick e4f5a6b # copy that commit here git switch main git reset --hard origin/main
The other way to end up in the wrong place is detached HEAD. Checking out an old commit to look at it (git switch --detach a1b2c3d, or git checkout a1b2c3d) puts you on no branch at all. Looking around is harmless. Committing there is the trap: those commits belong to no branch, and when you switch away, git warns that you're leaving them behind. Give them a branch before you leave, with git switch -c <name>.
$ git status On branch main Your branch is ahead of 'origin/main' by 1 commit. (use "git push" to publish your local commits)
$ git switch main Warning: you are leaving 1 commit behind, not connected to any of your branches: 38ddf90 Try new layout If you want to keep it by creating a new branch, this may be a good time to do so with: git branch <new-branch-name> 38ddf90 Switched to branch 'main'
Try it on your machine: on main in your practice repository, make a commit you haven't pushed. Move it to a new branch with git switch -c, then put main back with git reset --hard origin/main. Check the result with git log --oneline --graph --all.
Loading your workspace…