You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GitHub Actions中捕获全局npm命令输出赋值给变量的实现方案

问题描述

在GitHub Actions中获取全局npm命令输出时存在异常:运行任意全局安装的lint类npm包(多款同类工具测试结果一致)时,流程会直接报错退出,错误信息为Process completed with exit code 1.。
相同bash命令在本地机器上可完全正常运行。

初始测试用的简化版工作流配置如下:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Set up Node.js
        uses: actions/setup-node@v3
        with:
          node-version: 16.13.2

      - name: Install npm package
        run: npm install markdownlint-cli --location=global

      - name: Run standard-markdown
        id: run_md_lint
        run: |
          VAR=$((markdownlint **/*.md --ignore node_modules) 2>&1)
          echo "::set-output name=LINT_RESULT::$VAR"

      - name: Run a one-line script
        run: echo "Resultes ${{ steps.run_md_lint.outputs.LINT_RESULT }}"

lint命令的预期输出可在GitHub Action运行日志中正常打印,但无法将运行结果捕获并保存到变量中,排查后判断为命令返回非0错误退出码时,当前步骤会直接终止,后续赋值逻辑不会执行。
报错日志截图

最终需求为捕获lint命令的输出内容,在PR创建时自动将结果添加到PR评论中,对应配置片段如下:

- name: Add PR comment
        uses: actions/github-script@v6
        with:
          script: |
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: "${{ steps.run_md_lint.outputs.LINT_RESULT }}"
            })

问题解决

经调整后问题已修复,核心注意事项如下:

  • 执行lint命令后追加|| true修改命令返回的退出状态,避免步骤因非0退出码直接终止,保证后续输出捕获逻辑正常执行。
  • set-output仅支持单行字符串传递,需要替换输出内容中的百分号、换行符、回车符等特殊字符,才能正常传递多行内容。
  • npm包需要使用-g参数进行全局安装,--location=global参数无法正常生效。

可正常运行的GitHub Action完整配置如下:

name: Lint the docs!
on:
  pull_request:
    branches: [ "main" ]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3

      # 配置Node.js环境
      - name: Set up Node.js
        uses: actions/setup-node@v3
        with:
          node-version: 16.13.2

      - name: Install markdownlint
        run: npm install -g markdownlint-cli

      - name: Run standard-markdown
        id: run_md_lint
        run: |
          LINT=$(((markdownlint **/*.md --ignore node_modules) 2>&1) || true)
          LINT="${LINT//'%'/'%25'}"
          LINT="${LINT//$'\n'/'%0A'}"
          LINT="${LINT//$'\r'/'%0D'}"
          echo "::set-output name=LINT_RESULT::$LINT"

      - name: Add PR comment
        uses: actions/github-script@v6
        with:
          script: |
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: `Lint results:
              ```bash
              ${{ steps.run_md_lint.outputs.LINT_RESULT }}
              ```
              `
            })

内容的提问来源于stack exchange,提问作者user3552105

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 07:27:38