Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether environment variable is empty

What is the nicest approach to check if environment variable is empty on Github action as a condition to a step? I've tried the trivial approach but it doesn't seem to work.

For example:

name: SimpleWorkflow

on:
  push:   

env:
  MULTI_LINE_ARG: |
  ARG1: value
jobs:
  update:
    runs-on: ubuntu-latest
    steps:
      - name: Fetching Local Repository
        uses: actions/checkout@master
      - name: run step if multiline not null
        if: ${{env.MULTI_LINE_ARG}} != ""
        run: echo multiline not null     

No matter how I've tried this I fail to properly check if env is empty.

like image 629
user14242404 Avatar asked Sep 12 '25 13:09

user14242404


1 Answers

Checking for environment variables

In case one added an environment variable as described at Creating configuration variables for an environment, one can use if: ${{ env.VAR_NAME == '' }} for checking.

The following example provides an example workflow for the environment variable TEXT.

on:
  workflow_dispatch:
  push:
env:
  env_text: ${{ vars.TEXT }}
jobs:
  greeting_job:
    runs-on: ubuntu-latest
    steps:
      - if: ${{ env.env_text == '' }}
        run: |
          echo "Empty text"
      - if: ${{ env.env_text != '' }}
        run: |
          echo "Text: '$env_text'"

In case the variable is not defined, the output is as follows:

result-for-unset-variable

In case the variable is defined, the output is as follows:

result-for-set-variable

Checking for secrets

Background: The issue of secrets not available to forks is known to GitHub folks, but no concrete activity announced: https://github.community/t/github-workflow-not-running-from-pull-request-from-forked-repository/16379/41?u=koppor

One can use output variables of steps to determine whether a secret is available.

The name of the secret in GitHub is SECRET.

- name: Check secrets presence
  id: checksecrets
  shell: bash
  run: |
    if [ \"$SECRET\" == \"\" ]; then
        echo \"secretspresent=NO\" >> $GITHUB_OUTPUT
    else
        echo \"secretspresent=YES\" >> $GITHUB_OUTPUT
    fi
  env:
    SECRET: ${{ secrets.SECRET }}
- name: Run step if secret is present
  if: (steps.checksecrets.outputs.secretspresent == 'YES')
  run: echo secret is present

Note: Solution adapted from https://github.community/t/if-expression-with-context-variable/16558/6?u=koppor.

like image 182
koppor Avatar answered Sep 15 '25 12:09

koppor