Skip to content
shellhacks.dev
CI/CD

Set an environment variable for later steps

Set an environment variable for the following steps of a job by appending to GITHUB_ENV. It does not change the current step, which is the usual surprise.

1 min read
Summarize in AI

A step sets a variable, and the next step needs it, but exporting in the shell only lasts for that one step.

Shell
export GITHUB_ENV=$(mktemp)
echo "BUILD_MODE=release" >> "$GITHUB_ENV"
echo "in the same step: ${BUILD_MODE:-unset}"
echo "file for the runner:"
cat "$GITHUB_ENV"
Text
in the same step: unset
file for the runner:
BUILD_MODE=release

Every step runs in its own process, so export ends with the step. The runner reads the file in GITHUB_ENV after the step and adds each name=value line to the environment of all later steps, which the workflow commands reference documents. The variable is unset in the step that wrote it, as the first line of output shows, because only the file changed.

To use the value in the same step, also run export BUILD_MODE=release. Writing a value taken from untrusted input, such as a pull request title, can inject extra variables through a newline, for example a LD_PRELOAD line, so validate it first. A temporary file stands in for the runner's here.

Share

More snippets

CI/CD

Check what changed in a pull request

List the files a pull request changed with git diff --name-only origin/main...HEAD. Three dots compare against the merge base, and a shallow checkout cannot do it.

2 min read
CI/CD

Print a warning annotation

Print ::warning file=...,line=...::message from a step to show an annotation on the run and in the pull request diff. Newlines in the text must be encoded.

1 min read
CI/CD

Run a script from the repo

Run a repository script from a workflow with run: ./script.sh only if Git stores it as executable. Otherwise the step fails with Permission denied, status 126.

2 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.