How to tell git branch name from commit hash?

前端 未结 4 1493
旧时难觅i
旧时难觅i 2021-02-19 01:52

I have a bash script which accepts a string of either a branch name (e.g., \"master\", or \"feature/foo\") or a commit hash (e.g. \"1234abcd\").

I have the repository c

4条回答
  •  说谎
    说谎 (楼主)
    2021-02-19 02:04

    You can use git show-ref:

    git show-ref --head | grep refs
    

    If it is empty, it is a SHA1 (or an invalid object, which isn't good).
    If not, it is a branch name.


    A better technique comes from "Validate if commit exists", using git merge-base:

    A branch name will result in a different string (the SHA1)

    C:\Users\vonc\prog\b2d>git merge-base master master
    de4accfd28c5f25fcc057d56996b83450be5dc60
    

    a SHA1 will result in the same result (or at least starts with the same result):

    C:\Users\vonc\prog\b2d>git merge-base 03949c3d3f88a378c6a08e57daa97059b52813f1 03949c3d3f88a378c6a08e57daa97059b52813f1
    03949c3d3f88a378c6a08e57daa97059b52813f1
    

    foobar will fail:

    C:\Users\vonc\prog\b2d>git merge-base xxx xxx
    fatal: Not a valid object name xxx
    

    That means something like:

    if [[ git merge-base $string $string ]]; then
      if [[ $(git merge-base $string $string) == $string* ]]; then
        echo "SHA1"
      else
        echo "branch"
      fi
    else
      echo "Not a valid object name '$string'"
    fi
    

提交回复
热议问题