GitHub Actions添加内容至Issue标题遇反引号报错求解决方案
解决GitHub Action中Issue标题含反引号导致的语法错误问题
问题场景
现有如下GitHub Action,用于给指定Issue的标题追加"UPDATED":
name: Appends "UPDATED" to specified issue's title on: workflow_dispatch: inputs: NAME: type: string jobs: update-issue: runs-on: ubuntu-latest steps: - uses: actions/github-script@v6.4.1 with: script: | const newTitle = `${{ github.event.inputs.NAME }} - UPDATED` github.issues.update({ issue_number: `1`, owner: `user`, repo: `my-repo`, title: newTitle })
当NAME参数传入的内容包含反引号(如"V")时,Action会抛出SyntaxError: Unexpected identifier错误。可通过以下命令本地复现:
act -j update-issue -v -s GITHUB_TOKEN="$(gh auth token)" -e payload.json
对应的payload.json内容:
{ "inputs": { "NAME": "`V`" } }
原因分析
参数替换后,脚本中的模板字符串会被输入的反引号破坏结构。例如替换后代码变为:
const newTitle = ``V` - UPDATED`
连续的反引号导致JavaScript语法解析失败,触发错误。
解决方案
方案一:改用普通字符串拼接
放弃模板字符串,使用单引号包裹输入内容并进行字符串拼接,避免反引号干扰语法结构:
name: Appends "UPDATED" to specified issue's title on: workflow_dispatch: inputs: NAME: type: string jobs: update-issue: runs-on: ubuntu-latest steps: - uses: actions/github-script@v6.4.1 with: script: | const newTitle = '${{ github.event.inputs.NAME }}' + ' - UPDATED' github.issues.update({ issue_number: 1, owner: 'user', repo: 'my-repo', title: newTitle })
方案二:通过环境变量传递参数(推荐)
利用github-script的环境变量传递功能,将输入值存入环境变量后再在脚本中读取,彻底避免模板字符串替换带来的语法问题:
name: Appends "UPDATED" to specified issue's title on: workflow_dispatch: inputs: NAME: type: string jobs: update-issue: runs-on: ubuntu-latest steps: - uses: actions/github-script@v6.4.1 env: ORIGINAL_TITLE: ${{ github.event.inputs.NAME }} with: script: | const newTitle = `${process.env.ORIGINAL_TITLE} - UPDATED` github.issues.update({ issue_number: 1, owner: 'user', repo: 'my-repo', title: newTitle })
方案三:转义输入中的反引号
对输入内容中的反引号进行转义处理,确保模板字符串结构完整:
name: Appends "UPDATED" to specified issue's title on: workflow_dispatch: inputs: NAME: type: string jobs: update-issue: runs-on: ubuntu-latest steps: - uses: actions/github-script@v6.4.1 with: script: | const originalTitle = `${{ github.event.inputs.NAME }}` const escapedTitle = originalTitle.replace(/`/g, '\\`') const newTitle = `${escapedTitle} - UPDATED` github.issues.update({ issue_number: 1, owner: 'user', repo: 'my-repo', title: newTitle })
推荐方案
优先选择方案二,环境变量传递的方式不仅能解决反引号问题,还能兼容更多特殊字符场景,安全性和稳定性更强。
内容的提问来源于stack exchange,提问作者JackPGreen
相关产品推荐
相关产品推荐

