我希望在我的网站上显示主分支最新的git提交ID(即SHA)作为标识符。
我该如何从git中获取此信息?
这个命令可以获取最新提交的SHA-1值
git rev-parse HEAD
我更倾向于使用git describe
而不是HEAD SHA1,因为它是一个更易读的方式来获取“构建ID”。例如:
git describe --abbrev=4 HEAD
如果您不关心标签,并且考虑到git describe
是一个外观命令,不应在脚本中使用,那么是的,git rev-parse
(一个内部命令)更合适。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"
}
下面的命令将返回 HEAD 的 SHA-1 值:
git log -1 --pretty="%H"
略显粗糙的代码:
git log | head -1 | sed s/'commit '//
您可以使用:
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.
git rev-parse master
可以得到你想要的结果。 - Alan Haggai Alavigit rev-parse master
或git rev-parse origin/master
或任何其他您想要提交ID的引用名称。 - Alan Haggai Alavi