Sub topic 12
Passing data between steps with GITHUB_OUTPUT
This chapter assumes you can read a workflow file (on, jobs, runs-on, steps) and run basic shell commands on a Linux runner. It also assumes you know the ${{ }} expression syntax and what a context is.
Why steps need a channel
Each run step starts its own shell. A shell variable set in one step is gone in the next. To hand a value forward, a step writes it to a special file, and the runner exposes it to later steps through the steps context.
Writing an output
The runner gives every step the path of a file in the GITHUB_OUTPUT environment variable. Append a line in the form name=value to that file. Give the step an id so you can refer to it later.
name: step-outputs
on: push
jobs:
demo:
runs-on: ubuntu-latest
steps:
- id: ver
run: |
echo "version=1.2.3" >> "$GITHUB_OUTPUT"
echo "sha_short=${GITHUB_SHA::7}" >> "$GITHUB_OUTPUT"
- name: Read the outputs
run: |
echo "Version: ${{ steps.ver.outputs.version }}"
echo "Commit: ${{ steps.ver.outputs.sha_short }}"The expression steps.ver.outputs.version is replaced with the value before the second step's shell starts. The id must be unique within the job and may contain letters, numbers, - and _.
Multiline values
The name=value form only works for a single line. For several lines, use a delimiter. Pick a delimiter that cannot appear in the value.
name: multiline-output
on: push
jobs:
demo:
runs-on: ubuntu-latest
steps:
- id: notes
run: |
{
echo "text<<EOF_NOTES"
echo "line one"
echo "line two"
echo "EOF_NOTES"
} >> "$GITHUB_OUTPUT"
- env:
NOTES: ${{ steps.notes.outputs.text }}
run: echo "$NOTES"Common errors
- Missing
id. Without anid,steps.<id>has nothing to point at, and the expression evaluates to an empty string. - Wrong file operator. Use
>>(append). With>you overwrite earlier outputs from the same step. - Reading in the same step. The output is available only to steps that come after the writing step. It is not readable in the step that wrote it.
- Old
set-outputsyntax. The::set-outputworkflow command is deprecated. Use the file. - Quoting. Outputs are always strings. A value like
trueis the text"true", so compare it assteps.x.outputs.flag == 'true'.
Using an output in a condition
Outputs work in if expressions, so one step can decide whether later steps run.
name: conditional-output
on: push
jobs:
demo:
runs-on: ubuntu-latest
steps:
- id: check
run: echo "changed=true" >> "$GITHUB_OUTPUT"
- name: Runs only when changed
if: steps.check.outputs.changed == 'true'
run: echo "Changes found"Exercise
A step with id build runs echo "path=dist/app.zip" > "$GITHUB_OUTPUT" after an earlier line in the same step wrote version=2. A later step prints ${{ steps.build.outputs.version }} and gets an empty string. What is the cause, and how do you fix it?
Show answer
The single > overwrites the file, which erases the version=2 line written earlier. Change it to >> so the line is appended and both outputs survive.