如何在GitHub Actions后续步骤中使用github-script的输出
问题分析
你的配置存在几个关键错误,导致无法成功传递PR变更文件的输出:
- 语法错误:
>> $GITHUB_ENV是Shell语法,不能直接在github-script的JavaScript代码中使用,且代码末尾多了无效的g字符。 - 输出方式不匹配:你试图通过
steps.bbb.outputs.FILES读取输出,但当前代码并未正确设置步骤输出,而是错误地尝试用Shell语法写入环境变量。
修正方案
以下是两种可行的实现方式:
方案1:通过步骤输出传递数据
使用github-script内置的core.setOutput方法设置步骤输出,后续步骤可直接读取:
steps: - name: Checkout code uses: actions/checkout@v4 - name: Get PR changed files id: changed-files uses: actions/github-script@v7 with: github-token: ${{ secrets.GITHUB_TOKEN }} script: | const response = await github.request('GET /repos/{owner}/{repo}/pulls/{pull_number}/files', { owner: context.repo.owner, repo: context.repo.repo, pull_number: context.payload.pull_request.number }); const files = response.data.map(file => file.filename); // 设置步骤输出,后续通过steps.changed-files.outputs.files访问 core.setOutput('files', files.join('\n')); # 取消注释启用Python环境(如果需要) # - name: Set up Python # uses: actions/setup-python@v2 - name: Execute Python script run: | echo "Changed files: ${{ steps.changed-files.outputs.files }}" # 将文件列表作为参数传递给Python脚本 python your_script.py "${{ steps.changed-files.outputs.files }}"
方案2:通过环境变量传递数据
使用core.exportVariable将文件列表写入环境变量,后续步骤通过环境变量读取:
steps: - name: Checkout code uses: actions/checkout@v4 - name: Get PR changed files id: changed-files uses: actions/github-script@v7 with: github-token: ${{ secrets.GITHUB_TOKEN }} script: | const response = await github.request('GET /repos/{owner}/{repo}/pulls/{pull_number}/files', { owner: context.repo.owner, repo: context.repo.repo, pull_number: context.payload.pull_request.number }); const files = response.data.map(file => file.filename); # 写入环境变量,后续通过$CHANGED_FILES访问 core.exportVariable('CHANGED_FILES', files.join('\n')); # 取消注释启用Python环境(如果需要) # - name: Set up Python # uses: actions/setup-python@v2 - name: Execute Python script run: | echo "Changed files: $CHANGED_FILES" # 将环境变量传递给Python脚本 python your_script.py "$CHANGED_FILES"
关键注意事项
- github-script运行在Node.js环境中,必须使用
@actions/core库提供的方法操作输出或环境变量,不能直接使用Shell语法。 - 如果文件路径包含空格或特殊字符,务必用引号包裹变量,避免解析错误。
内容的提问来源于stack exchange,提问作者KaramJaber
相关产品推荐
相关产品推荐

