Search code examples
gitgithubyamlgithub-actions

How to get short Github SHA of the `main` branch in Github Actions?


I want to get a short Git SHA for the main branch in my Github actions workflow.

I referred to multiple answers but their SHA commit is (be it GITHUB environment or the git command) of the branch that triggered the workflow. I want the last short commit of the Github main branch. How do I do that?


Solution

  • If you're triggering the action on a pull request, then github.event.pull_request.base.sha is the current SHA of the HEAD of the PR's target branch. You can use that variable for the full SHA, or get a shortened SHA by passing that to git rev-parse:

    git rev-parse --short ${{ github.event.pull_request.base.sha }}
    

    If you aren't triggering on a pull request, or if you want to hedge against the chance that somebody might open a PR against a different branch, then you'll need to do something a little more complicated:

    git ls-remote -q | grep refs/heads/main$ | awk '{print $1}' | xargs git rev-parse --short
    

    (use refs/heads/master$ if your default branch is named master, or refs/heads/production$ if it's named production, etc.)