Home > Software engineering >  How to create GitHub environment variables with object-like syntax to test a bash script
How to create GitHub environment variables with object-like syntax to test a bash script

Time:01-03

I'm currently coding a shell script for my GitHub Workflow and I want to test it locally.

However, it depends on an env variable provided by GitHub that consists of multiple nested segments, like a Javascript object for example.

my-bash-file.sh

PAYLOAD=${github.event.client_payload}
echo "$PAYLOAD"

How would I declare and inject such a kind of env variable locally when calling my script?

CodePudding user response:

While you can define environment variables containing dots you won't be able to reference them from bash as identifiers can consist only of alphanumeric characters and underscores.

However, you can access them using other languages, like python. Call it my-python for example:

#! /usr/bin/env python3

import os

payload=os.environ['github.event.client_payload']
print(f'payload={payload}')

invoking it as

env github.event.client_payload=hello ./my-python

produces

payload=hello

CodePudding user response:

I think I understand what you're trying to do. You're running a shell script as part of a GitHub action that looks something like this:

jobs:
  my-job:
    runs-on: ubuntu-latest
    steps:
      - name: Install pre-commit
        run: |
          PAYLOAD=${github.event.client_payload}
          echo "$PAYLOAD"

The best solution is to not reference github template variables directly in your shell script. Write it like this instead:

jobs:
  my-job:
    runs-on: ubuntu-latest
    steps:
      - name: Install pre-commit
        env:
          PAYLOAD: "${github.event.client_payload}"
        run: |
          echo "$PAYLOAD"

This keeps the github template variable out of your script and instead uses it to set the PAYLOAD environment variable before the script runs. If you want to run the same script locally, you would just need to set the same PAYLOAD environment variable.


The examples here show a script embedded in the GitHub workflow; that's because there's no way to use a template variable embedded in a script file as you've shown in your question. If your workflow tried to run a script my-bash-file.sh that contained:

#!/bin/sh
PAYLOAD=${github.event.client_payload}
echo "$PAYLOAD"

It would fail with:

my-bash-file.sh: line 2: ${github.event.client_payload}: bad substitution
  • Related