How to git-commit from a branch to a detached HEAD?

318 views Asked by At

My ref HEAD points the branch foo, that points to the commit 123abc; and I have some staged work.

How to git commit that work, moving the HEAD to the newly created commit, but without advancing the branch?

(hence: leaving foo point to 123abc)

Is it possible to do it with a single git command?

3

There are 3 answers

1
Quentin On BEST ANSWER

Simply detach, then commit:

git checkout --detach
git commit -m "Commit as usual"
1
Tim Biegeleisen On

You could just commit and then do a reset:

# from foo branch
git commit -m 'your work here'
git reset --soft HEAD~1

This would move the HEAD pointer back one commit to 123abc, but would also stage all the work in that commit.

There are other types of reset (mixed, hard), which do variants of the above. Without knowing your end goal, it isn't clear what kind of reset you should use. In general, though, moving the HEAD back one commit is something you would do if you wanted to rewrite the prior HEAD commit.

2
ElpieKay On

If HEAD is directly pointing to commit 123abc, it's already on detached HEAD state instead of on foo. git commit will create a new commit and move HEAD to the new commit, leaving foo unmoved.

If HEAD points at refs/heads/foo and refs/heads/foo points at 123abc, you can run git checkout 123abc and then make the commit.