How to tell git branch name from commit hash?

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

    If you would like a robust mechanism to tell relative names (e.g. you SHA1 is possibly one or so commits behind a named branch), you can use git name-rev to resolve it.

    Examples:

    $ git config remote.upstream.url
    https://github.com/RobotLocomotion/drake.git
    
    $ git log --oneline -n 5
    7530a95 Merge pull request #5743 from soonho-tri/pr-reformat-mathematical_program
    ebc8f25 Suppresses console output of speed_bump.obj genrule. (#5726)
    d8b9a0b Merge pull request #5735 from david-german-tri/namespaces
    79e10e8 Remove redundant 'symbolic::' prefix from mathematical_program code
    b68b590 Clean up mathematical_program code by adding using std::*
    
    $ git name-rev HEAD
    HEAD master
    $ git name-rev 79e10e8
    79e10e8 master^2
    $ git name-rev HEAD~20
    HEAD~20 remotes/origin/issue/5646_return_binding~3
    

    Reference: Git Tips (old commit)

    UPDATE: As @kporter mentioned, there is also the --name-only flag (with new commits as of 2020/04/21):

    $ git name-rev HEAD
    HEAD tags/last_sha_with_original_matlab~313
    $ git name-rev --name-only HEAD~20
    tags/last_sha_with_original_matlab~333
    

    Command-Line Reference: git name-rev

提交回复
热议问题