You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GitHub Workflow中获取提交的短SHA值?

Can I use the short SHA in a global GitHub Workflow environment variable?

Absolutely, this is totally feasible! You don’t need to run git rev-parse --short HEAD directly—GitHub Actions provides straightforward ways to get the short SHA for your global environment variable. Here are two reliable approaches:

Method 1: Use GitHub’s substring expression (simplest for global env)

You can truncate the full ${{ github.sha }} to the first 7 characters (the default length returned by git rev-parse --short HEAD) using the built-in substring function directly in your global env section:

name: continuous integration
on:
  push:
    branches:
      - '**'
env:
  IMAGE: docker.pkg.github.com/${{ github.repository }}/jactor-persistence:${{ github.sha | substring(0,7) }}

This will give you exactly the same short SHA as the git command, and it’s available to all jobs in your workflow without extra steps.

Method 2: Set via a step (for custom length or validation)

If you need a different short SHA length (e.g., 10 characters instead of 7) or want to explicitly validate the value first, you can set the variable in an initial setup job and pass it to subsequent jobs:

name: continuous integration
on:
  push:
    branches:
      - '**'
jobs:
  setup-sha:
    runs-on: ubuntu-latest
    outputs:
      short_sha: ${{ steps.get-sha.outputs.short_sha }}
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
      - name: Get custom short SHA
        id: get-sha
        run: echo "short_sha=$(git rev-parse --short=10 HEAD)" >> $GITHUB_OUTPUT
  build-image:
    needs: setup-sha
    runs-on: ubuntu-latest
    env:
      IMAGE: docker.pkg.github.com/${{ github.repository }}/jactor-persistence:${{ needs.setup-sha.outputs.short_sha }}
    steps:
      # Add your build/push steps here

Either method works, but the first approach is cleaner for a global environment variable that’s used across all jobs.

内容的提问来源于stack exchange,提问作者jactor-rises

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 10:02:45