如何在GitHub Action的Bash语法中移除PR标题中的撇号
GitHub Action创建Issue失败的问题解决与优化
一、撇号导致工作流失败的原因
你当前的代码用title='${{ github.event.pull_request.title }}'给变量赋值,当PR标题里包含撇号(比如Don't enable xyz)时,Bash会把标题里的'当成字符串的闭合符。展开后代码会变成title='Don't',Bash会认为Don是完整字符串,剩下的t'是无效的命令片段,直接触发语法错误,整个步骤执行失败,自然没法创建Issue。
二、删除PR标题中撇号的方法
先解决变量赋值的语法问题,再做撇号删除:
- 改用双引号包裹标题变量,避免单引号的闭合冲突:
title="${{ github.event.pull_request.title }}" - 用Bash参数替换语法删除所有撇号:
这样clean_title="${title//\'/}"Don't enable xyz就会变成Dont enable xyz,之后把clean_title用到Issue标题里即可。
三、兼容所有标题内容的优化方案
手动替换字符容易遗漏特殊字符(比如双引号、反斜杠、换行符),推荐两种更可靠的方式:
方案1:用jq自动处理JSON转义
jq是专门处理JSON的工具,能自动转义所有JSON不允许的特殊字符,确保构造的JSON格式合法:
- name: create-issue id: create-issue run: | pr_number=${{ github.event.pull_request.number }} writer=${{ steps.get-writer.outputs.writer }} pr_title="${{ github.event.pull_request.title }}" # 用jq构造合法JSON,自动处理转义 data=$(jq -n \ --arg pr_num "$pr_number" \ --arg title "$pr_title" \ --arg writer "$writer" \ --arg version "$version" \ '{ title: "Document PR #\($pr_num) - \($title) \($version)", body: "Determine whether #\($pr_num) needs any release notes or other documentation updates", assignees: [\($writer)], labels: ["Area: Documentation"] }') # 调用GitHub API创建Issue(示例用gh CLI) gh issue create --title "$(jq -r '.title' <<< "$data")" --body "$(jq -r '.body' <<< "$data")" --assignee "$writer" --label "Area: Documentation"
方案2:直接用GitHub CLI创建Issue
GitHub CLI的gh issue create命令会自动处理标题、内容里的所有特殊字符,不需要手动转义,代码更简洁:
- name: create-issue id: create-issue run: | gh issue create \ --title "Document PR #${{ github.event.pull_request.number }} - ${{ github.event.pull_request.title }} $version" \ --body "Determine whether #${{ github.event.pull_request.number }} needs any release notes or other documentation updates" \ --assignee "${{ steps.get-writer.outputs.writer }}" \ --label "Area: Documentation"
内容的提问来源于stack exchange,提问作者mzbu
相关产品推荐
相关产品推荐

