如何在git中获取主分支的最新提交id?

83

我希望在我的网站上显示主分支最新的git提交ID(即SHA)作为标识符。

我该如何从git中获取此信息?

5个回答

134

这个命令可以获取最新提交的SHA-1值

git rev-parse HEAD

9
我认为这种“管道”方法对于OP所需的基于脚本的解决方案更好,而不是我下面建议的“瓷器”方法(即“git log…”)。 - Jeet
1
如何在master分支上获取最新提交的SHA-1? - andy
4
git rev-parse master 可以得到你想要的结果。 - Alan Haggai Alavi
@AlanHaggaiAlavi 这在本地 Git 仓库中有效,那么在从远程服务器(如 GitHub)克隆的仓库中应该使用什么? - Kasun Siyambalapitiya
1
Kasun Siyambalapitiya: 这应该适用于任何Git存储库。您可以使用git rev-parse mastergit rev-parse origin/master或任何其他您想要提交ID的引用名称。 - Alan Haggai Alavi

40

我更倾向于使用git describe而不是HEAD SHA1,因为它是一个更易读的方式来获取“构建ID”。例如:

git describe --abbrev=4 HEAD
如果您不关心标签,并且考虑到git describe是一个外观命令,不应在脚本中使用,那么是的,git rev-parse(一个内部命令)更合适。
但同样地,如果您希望在您的网站上显示SHA1作为标识,我会选择:
git rev-parse --short HEAD
为了仅显示SHA1的前7个数字,请使用以下命令:git rev-parse --short=7 HEAD
git rev-parse HEAD(意味着所有40个数字)仍然很有用,当您想要检查您刚刚部署的是否确实是HEAD所指的内容时。
例如,参见此部署脚本
它首先触发一个更新:
#If requested, perform update before gathering information from repos.
if $update; then
    echo "Updating fred-official."
    cd "$fredDir"
    git_update
    if ! [[ "$forceFredID" = "" ]]
    then
        checkGitID "$forceFredID"
    fi
    echo "Updating website repo."
    cd "$websiteDir"
    git_update
    if ! [[ "$forceWebsiteID" = "" ]]
    then
        checkGitID "$forceWebsiteID"
    fi
    cd "$startingDir"
fi
更新本身会刷新网站内容:
# Discard any local changes, update remote branches and tags, and
# check out to the latest master branch.
git_update() {
    #To update tags and branches.
    git remote update
    git clean -dfx
    git reset --hard origin/master
}

然后它使用 git rev-parse HEAD 来检查刚刚被检出的内容:

function checkGitID {
    checkID=$1
    echo Checking git ID is "$checkID"
    if ! git checkout "$checkID"
    then
        echo Failed to checkout "$checkID"
        exit 4
    fi
    if ! actualID=$(git rev-parse --verify HEAD)
    then
        echo Failed to verify "$checkID"
        git checkout master
        exit 5
    fi
    if ! [[ "$actualID" = "$checkID" ]]
    then
        echo Git verification failed, something very bad is happening
        exit 6
    fi
    echo Git ID verified: "$checkID"
}

20

下面的命令将返回 HEAD 的 SHA-1 值:

git log -1 --pretty="%H"

3

略显粗糙的代码:

git log | head -1 | sed s/'commit '//


1

您可以使用:

git describe --always --dirty


   --dirty[=<mark>], --broken[=<mark>]
       Describe the state of the working tree. When the working tree matches HEAD, the output is the same
       as "git describe HEAD". If the working tree has local modification "-dirty" is appended to it. If a
       repository is corrupt and Git cannot determine if there is local modification, Git will error out,
       unless ‘--broken’ is given, which appends the suffix "-broken" instead.

   --all
       Instead of using only the annotated tags, use any ref found in refs/ namespace. This option enables
       matching any known branch, remote-tracking branch, or lightweight tag.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接