How to find the current git branch in detached HEAD state

前端 未结 6 1790
遥遥无期
遥遥无期 2020-12-04 12:58

I can find the current git branch name by doing either of these:

git branch | awk \'/^\\*/ { print $2 }\'
git describe --contains --all HEAD
<
6条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 13:48

    A sed solution:

    git log -1 --pretty=%D HEAD | sed 's/.*origin\///g;s/, .*//g'
    

    This uses log to check the last item for its presence on a branch. Then sed finds the branch preceded by origin/ and removes the phrase and everything before it. Then sed does another removal of any possible additional listed branches (comma and everything after it). The reason last log was used as a sanity check to ensure this detached HEAD is not a commit above known branch HEADs.

    If this is empty, failsafe logic can be implemented to label the branch "detached" (or "undefined"?) or to ensure it's up-to-date or rolled back to the tip of a known HEAD.

提交回复
热议问题