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

Github Action写入JSON文件时引号被剥离的问题咨询

解决GitHub Actions写入JSON输入时引号丢失的问题

当你通过workflow_dispatch传入JSON格式内容,用echo "${{ github.event.inputs.file_contents}}" > temp_file写入文件时,引号被剥离的核心原因是GitHub Actions表达式插值会对特殊字符转义,而shell执行时会解析这些转义,导致引号丢失。以下是几种可靠的解决方法:

方法1:使用环境变量中转

将输入内容赋值给环境变量,再通过环境变量写入文件,环境变量会保留正确的转义信息:

on:
  workflow_dispatch:
    inputs:
      file_contents:
        description: 'File contents'
        required: true

jobs:
  write-file:
    runs-on: ubuntu-latest
    steps:
      - name: Write file via env var
        env:
          RAW_CONTENT: ${{ github.event.inputs.file_contents }}
        run: |
          echo "$RAW_CONTENT" > temp_file
          cat temp_file

方法2:使用Here Document( heredoc)

利用带单引号的here-doc可以避免shell解析内容中的特殊字符,实现原样写入:

on:
  workflow_dispatch:
    inputs:
      file_contents:
        description: 'File contents'
        required: true

jobs:
  write-file:
    runs-on: ubuntu-latest
    steps:
      - name: Write file via heredoc
        run: |
          cat > temp_file << 'EOF'
          ${{ github.event.inputs.file_contents }}
          EOF
          cat temp_file

注意:EOF必须用单引号包裹,这样里面的内容会被当作纯文本处理,不会被shell解析。

方法3:使用printf替代echo

printf的输出行为比echo更稳定,能更好地保留特殊字符:

on:
  workflow_dispatch:
    inputs:
      file_contents:
        description: 'File contents'
        required: true

jobs:
  write-file:
    runs-on: ubuntu-latest
    steps:
      - name: Write file via printf
        run: |
          printf "%s\n" "${{ github.event.inputs.file_contents }}" > temp_file
          cat temp_file

这些方法都不需要依赖Base64编码,能直接实现JSON内容的原样写入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 19:48:24