How to tell git branch name from commit hash?

前端 未结 4 1510
旧时难觅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:21

    As @VonC and @hek2mgl mentioned, this may not be a one or the other test. You could slightly modify your script to something like this (borrowed from this SO answer:

    #!/bin/bash
    commit_or_branch="$1"
    cd /path/to/my_repo
    git fetch
    if git branch | grep $commit_or_branch 2> /dev/null
    then
        echo "it's a branch"
    fi
    
    if git cat-file -e $commit_or_branch 2> /dev/null
    then
      echo "it's a commit"
    fi
    

    Note that this only tests for local branches.. see this post if you're interested in remote branches.

提交回复
热议问题