在GitHub Actions中获取Shell标准输出并发布为PR评论
修复GitHub Actions获取Shell输出并发布PR评论的问题
原配置的核心错误
第二个步骤的set-output命令语法完全错误,没有正确读取output.txt的内容,导致输出值无法传递到后续评论步骤。
修正后的配置方案(保留中间文件)
- name: Run shell command and save output id: sh run: bash ./update/commands.sh | tee output.txt - name: Extract coverage output id: get_coverage run: | # 旧语法:读取文件内容并设置输出变量 echo "::set-output name=coverage::$(cat output.txt)" # 推荐使用官方新语法 # echo "coverage=$(cat output.txt)" >> $GITHUB_OUTPUT - uses: mshick/add-pr-comment@v1 with: message: | Coverage report: ``` ${{ steps.get_coverage.outputs.coverage }} ``` 🌏 repo-token: ${{ secrets.GITHUB_TOKEN }} repo-token-user-login: 'github-actions[bot]' allow-repeats: false
更简洁的优化方案(无需中间文件)
直接在执行脚本的步骤中捕获输出,省去创建中间文件的环节:
- name: Run shell command and capture output id: get_coverage run: | # 直接捕获脚本输出并设置到步骤输出 echo "coverage=$(bash ./update/commands.sh)" >> $GITHUB_OUTPUT - uses: mshick/add-pr-comment@v1 with: message: | Coverage report: ``` ${{ steps.get_coverage.outputs.coverage }} ``` 🌏 repo-token: ${{ secrets.GITHUB_TOKEN }} repo-token-user-login: 'github-actions[bot]' allow-repeats: false
关键修正点说明
- 原命令中
< output.txt)是无效语法,必须用$(cat output.txt)读取文件内容并嵌入到输出变量中。 - 优先使用
echo "KEY=VALUE" >> $GITHUB_OUTPUT的新语法,这是GitHub Actions官方当前推荐的步骤输出设置方式,替代旧的::set-output语法。 - 用代码块(```)包裹输出内容,能在PR评论中保留原格式,提升可读性。
内容的提问来源于stack exchange,提问作者Ahmed_Platform_Eng
相关产品推荐
相关产品推荐

