How do I get the commit id of the head of master in git?

Solution 1:

This command will get you the latest commit's SHA-1

git rev-parse HEAD

Solution 2:

Instead of the HEAD SHA1, I would rather go with git describe, as a more readable way to get a "build id". For instance:

git describe --abbrev=4 HEAD

If you don't care about tags, and considering that git describe is a porcelain command, which shouldn't be used in a script, then, yes, git rev-parse (a plumbing command) is more appropriate.

But again, if you are to display a SHA1 on your website as an id, I would go with:

git rev-parse --short HEAD

(In order to display only the first 7 digits of the SHA1)


git rev-parse HEAD (meaning the all 40 digits) is still useful, when you want to check if what you just deployed is indeed what HEAD refers to.
See for instance this deployment script:

It first triggers an update:

#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

The update itself refreshes the website content:

# 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
}

And then it uses git rev-parse HEAD to check what just has been checked out:

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"
}