GitHub Actions — How to Get the Short Git Commit Hash

GitHub Actions is a great integration tool in the software platform. For example, you may run your test suite when pushing to the repository or deployment when pushing to a branch connected to a deployed environment.

We’re using GitHub Actions for both examples: running our test suite and deployments. When deploying, we’re using the short git commit hash as part of the release identifier. But there’s one downside in GitHub Actions: they don’t provide the short git commit hash as a variable by default.

This tutorial shows you how to get the short, seven-character git commit hash within GitHub Actions.

GitHub Actions Series Overview

Use the Short Git Commit Hash in GitHub Actions

GitHub Actions provide a comprehensive set of contextual information. For example, you’re receiving the context data for the environment or the job or specific github data.

The github context contains the github.sha variable that triggered the workflow. It’s the git commit SHA in full length, like ffac537e6cbbf934b08745a378932722df287a53.

You can retrieve the short commit SHA using bash parameter expansion. With parameter expansion, you can extract a substring from a given variable. You’re providing an offset and the substring length.

Here’s an example outlining the use of parameter expansion to retrieve the short git commit hash:

github_sha_hash=${{ github.sha }}  
github_sha_short="${github_sha_hash:0:7}"  

GitHub Actions Example Workflow With Short Git Commit Hash

The following GitHub Actions workflow shows you how to get and use short git SHA. We’re retrieving the full github.sha context variable and using parameter expansion to get the first seven characters from it. We’re also storing the short commit hash within a local github_sha_short variable that can be used later, in our case to echo out the value:

name: Production Deployment

on:  
  workflow_run:
    workflows: [Run tests]

jobs:  
  deploy:
    runs-on: ubuntu-24.04

    steps:
      …

      - name: Run your script
        run: |
          github_sha_hash=${{ github.sha }}
          github_sha_short="${github_sha_hash:0:7}"

          echo "GitHub Short Commit Hash hash: ${github_sha_short}"

That’s it!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.