Today I Learned

Getting Short SHA in GitHub Actions Pipeline

When working with GitHub Actions, you may often find yourself needing to reference the commit associated with a build. While Git provides a full SHA hash for every commit, it can be cumbersome to work with in logs or when passing it between steps. Thankfully, GitHub Actions gives us the ability to easily access a shortened version of this SHA.

What is a Short SHA?

A “short SHA” refers to a truncated version of the full SHA-1 hash of a commit. Instead of using the full 40-character string, the short SHA typically consists of the first 7 characters, which are unique enough in most cases to identify a commit.

Accessing the Short SHA in Your GitHub Actions Workflow

To retrieve the short SHA of the commit currently being built in a GitHub Actions workflow, you can make use of the built-in environment variables that GitHub provides. Specifically, the GITHUB_SHA variable contains the full commit SHA. To convert it to a short SHA, you may use shell commands in a step.

Here’s how you can access and use the short SHA in your GitHub Actions pipeline:

Example Workflow

name: Get Short SHA Example

on: [push]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v2

      - name: Get Short SHA
        id: get_short_sha
        run: echo "SHORT_SHA=$(echo $GITHUB_SHA | cut -c1-7)" >> $GITHUB_ENV
      
      - name: Use Short SHA
        run: echo "Short SHA is $SHORT_SHA"

Breakdown of the Example

  1. Checkout code: The actions/checkout action is run to retrieve the repository’s code.

  2. Get Short SHA: In this step, we extract the first 7 characters of the GITHUB_SHA using the cut command. This value is then stored in the GitHub Actions environment using the special $GITHUB_ENV variable.

  3. Use Short SHA: Finally, you can use the short SHA in subsequent steps or actions as needed, simply referencing the SHORT_SHA variable.

Why Use Short SHA?

  • Readability: Short SHAs are easier to read and manage in logs.
  • Conciseness: They save space in notifications, comments, or messages where space is limited.
  • Simplicity: It’s easier to copy, paste, and share when collaborating with teammates.

With this simple approach, you can leverage short SHAs in your GitHub Actions workflows, making your pipelines cleaner and more efficient.