1

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?

Aviral Srivastava
  • 4,058
  • 8
  • 29
  • 81

1 Answers1

2

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.)

Jim Redmond
  • 4,139
  • 1
  • 14
  • 18
  • I did this: ```git fetch --prune --unshallow export MAIN_BRANCH_SHA_SHORT=$(git rev-parse --short origin/main) echo "::set-output name=MAIN_BRANCH_SHA_SHORT::$MAIN_BRANCH_SHA_SHORT"``` – Aviral Srivastava May 05 '23 at 05:12
  • 1
    "grep + awk" can be shortened to just awk: `awk '/refs\/heads\/main$/{print $1}'`. – hlovdal May 05 '23 at 08:51