{"meta":{"title":"在工作流中使用 GitHub CLI","intro":"可以在 GitHub CLI 工作流中使用 GitHub Actions 编写脚本。","product":"GitHub Actions","breadcrumbs":[{"href":"/zh/actions","title":"GitHub Actions"},{"href":"/zh/actions/how-tos","title":"操作方法"},{"href":"/zh/actions/how-tos/write-workflows","title":"编写工作流"},{"href":"/zh/actions/how-tos/write-workflows/choose-what-workflows-do","title":"选择工作流执行的操作"},{"href":"/zh/actions/how-tos/write-workflows/choose-what-workflows-do/use-github-cli","title":"使用 GitHub CLI"}],"documentType":"article"},"body":"# 在工作流中使用 GitHub CLI\n\n可以在 GitHub CLI 工作流中使用 GitHub Actions 编写脚本。\n\n> \\[!NOTE]\n> 若要详细了解 GitHub CLI，请参阅“[关于 GitHub CLI](/zh/github-cli/github-cli/about-github-cli)”。\n\nGitHub CLI 预安装在所有 GitHub 托管的运行程序上。 对于使用 GitHub CLI 的每个步骤，必须将调用 `GH_TOKEN` 的环境变量设置为具有所需范围的令牌。\n\n可以执行任何 GitHub CLI 命令。 例如，此工作流使用 `gh issue comment` 子命令在打开问题时添加注释。\n\n```yaml copy\nname: Comment when opened\non:\n  issues:\n    types:\n      - opened\njobs:\n  comment:\n    runs-on: ubuntu-latest\n    steps:\n      - run: gh issue comment $ISSUE --body \"Thank you for opening this issue!\"\n        env:\n          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          ISSUE: ${{ github.event.issue.html_url }}\n```\n\n还可以通过 GitHub CLI 执行 API 调用。 例如，此工作流首先使用 `gh api` 子命令查询 GraphQL API 并分析结果。 然后，它将结果存储在可在后续步骤中访问的环境变量中。 在第二步中，它使用 `gh issue create` 子命令创建包含第一步中信息的问题。\n\n```yaml copy\nname: Report remaining open issues\non:\n  schedule:\n    # Daily at 8:20 UTC\n    - cron: '20 8 * * *'\njobs:\n  track_pr:\n    runs-on: ubuntu-latest\n    steps:\n      - run: |\n          numOpenIssues=\"$(gh api graphql -F owner=$OWNER -F name=$REPO -f query='\n            query($name: String!, $owner: String!) {\n              repository(owner: $owner, name: $name) {\n                issues(states:OPEN){\n                  totalCount\n                }\n              }\n            }\n          ' --jq '.data.repository.issues.totalCount')\"\n\n          echo 'NUM_OPEN_ISSUES='$numOpenIssues >> $GITHUB_ENV\n        env:\n          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          OWNER: ${{ github.repository_owner }}\n          REPO: ${{ github.event.repository.name }}\n      - run: |\n          gh issue create --title \"Issue report\" --body \"$NUM_OPEN_ISSUES issues remaining\" --repo $GITHUB_REPOSITORY\n        env:\n          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n```"}