69
votes

In GitHub Actions, I'd like to evaluate a bash expression and then assign it to an environment variable:

    - name: Tag image
      env:
        GITHUB_SHA_SHORT: ${{ $(echo $GITHUB_SHA | cut -c 1-6) }}
      ..do other things...

However, this naive attempt has failed. According to the docs this doesn't seem to be supported; a somewhat clean workaround would be fine.

2
Maybe set-env would work in a previous step. help.github.com/en/articles/… - peterevans

2 Answers

129
votes

The original answer to this question used the Actions runner function set-env. Due to a security vulnerability set-env is being deprecated and should no longer be used.

This is the new way to set environment variables.

name: my workflow
on: push
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Set env
      run: echo "GITHUB_SHA_SHORT=$(echo $GITHUB_SHA | cut -c 1-6)" >> $GITHUB_ENV
    - name: Test
      run: echo $GITHUB_SHA_SHORT

Setting an environment variable echo "{name}={value}" >> $GITHUB_ENV

Creates or updates an environment variable for any actions running next in a job. The action that creates or updates the environment variable does not have access to the new value, but all subsequent actions in a job will have access. Environment variables are case-sensitive and you can include punctuation.

(From https://help.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-environment-variable)

Example using the output to $GITHUB_ENV method:

    echo "GITHUB_SHA_SHORT=$(echo $GITHUB_SHA | cut -c 1-6)" >> $GITHUB_ENV

This is an alternative way to reference the environment variable in workflows.

    - name: Test
      run: echo ${{ env.GITHUB_SHA_SHORT }}
-3
votes

The documentation https://docs.github.com/en/free-pro-team@latest/actions/reference/environment-variables#about-environment-variables describes 2 ways of defining environment-variables.

To set custom environment variables, you need to specify the variables in the workflow file. You can define environment variables for a step, job, or entire workflow using the jobs.<job_id>.steps[*].env, jobs.<job_id>.env, and env keywords.

steps:
  - name: Hello world
    run: echo Hello world $FIRST_NAME $middle_name $Last_Name!
    env:
      FIRST_NAME: Mona
      middle_name: The
      Last_Name: Octocat

You can also use the GITHUB_ENV environment file to set an environment variable that the following steps in a workflow can use. The environment file can be used directly by an action or as a shell command in a workflow file using the run keyword.