GitHub CLI (gh) — Comprehensive Skill
Version: gh 2.66.1+
Auth: gh auth login or set GH_TOKEN env var
Always use --repo OWNER/REPO (or -R) when not inside a git repo directory.
Table of Contents
- 1. Authentication & Config
- Repositories
- Issues
- Pull Requests
- GitHub Actions (Runs & Workflows)
- Releases
- Gists
- Search
- Labels
- Secrets & Variables
- Caches
- Projects V2
- API (REST & GraphQL)
- Extensions
- Codespaces
- Copilot
- Other Commands
- JSON Output & Formatting
- Environment Variables
- Advanced Patterns
- Tips & Gotchas
1. Authentication & Config
Auth
CODEBLOCK0
Required scopes by feature:
| Feature | Scope needed |
|---|
| Basic repo/PR/issue ops | INLINECODE5 |
| Gists |
gist |
| Read org membership |
read:org |
| Projects V2 |
project |
| Delete repos |
delete_repo |
| Actions workflows |
workflow |
| Read user profile |
user |
Config
CODEBLOCK1
Git credential setup
CODEBLOCK2
2. Repositories
Create
CODEBLOCK3
Clone
CODEBLOCK4
Fork
CODEBLOCK5
View
CODEBLOCK6
JSON fields for repo: INLINECODE12
List
CODEBLOCK7
Edit
CODEBLOCK8
Delete / Archive
CODEBLOCK9
Rename
CODEBLOCK10
Set Default
CODEBLOCK11
Sync (Fork ↔ Upstream)
CODEBLOCK12
3. Issues
Create
CODEBLOCK13
List
CODEBLOCK14
JSON fields for issues: INLINECODE13
View
CODEBLOCK15
Edit
CODEBLOCK16
Close / Reopen
CODEBLOCK17
Comment
CODEBLOCK18
Pin / Unpin
CODEBLOCK19
Transfer
CODEBLOCK20
Lock / Unlock
CODEBLOCK21
Develop (linked branches)
CODEBLOCK22
Delete
CODEBLOCK23
4. Pull Requests
Create
CODEBLOCK24
List
CODEBLOCK25
JSON fields for PRs: INLINECODE14
View
CODEBLOCK26
Checkout
CODEBLOCK27
Diff
CODEBLOCK28
Merge
CODEBLOCK29
Review
CODEBLOCK30
Checks (CI Status)
CODEBLOCK31
JSON fields for checks: INLINECODE15
Edit
CODEBLOCK32
Close / Reopen
CODEBLOCK33
Ready / Draft
CODEBLOCK34
Update Branch
CODEBLOCK35
Comment
CODEBLOCK36
Lock / Unlock
CODEBLOCK37
5. GitHub Actions (Runs & Workflows)
Workflow Runs
CODEBLOCK38
JSON fields for runs: INLINECODE16
Workflows
CODEBLOCK39
6. Releases
Create
CODEBLOCK40
List / View
CODEBLOCK41
Download
CODEBLOCK42
Edit / Upload / Delete
CODEBLOCK43
7. Gists
CODEBLOCK44
8. Search
Repos
CODEBLOCK45
Issues
CODEBLOCK46
Pull Requests
CODEBLOCK47
Commits
CODEBLOCK48
Code
CODEBLOCK49
9. Labels
CODEBLOCK50
10. Secrets & Variables
Secrets (encrypted)
CODEBLOCK51
Variables (plaintext)
CODEBLOCK52
11. Caches
CODEBLOCK53
12. Projects V2
⚠️ Requires project scope: gh auth refresh -s project
Projects V2 uses the GraphQL-based ProjectsV2 API. The CLI provides commands for most operations, but some advanced field mutations require direct GraphQL via gh api graphql.
List Projects
CODEBLOCK54
Create
CODEBLOCK55
View
CODEBLOCK56
Edit
CODEBLOCK57
Close / Reopen / Delete
CODEBLOCK58
Copy
CODEBLOCK59
Link / Unlink to Repository or Team
CODEBLOCK60
Mark as Template
CODEBLOCK61
Fields
CODEBLOCK62
Field data types: TEXT, SINGLE_SELECT, DATE, NUMBER
(Iteration fields must be created via the web UI or GraphQL)
Items
CODEBLOCK63
Getting Node IDs (Essential for item-edit)
The item-edit command requires node IDs for the item, field, project, and option. Here's how to get them:
CODEBLOCK64
Projects V2 via GraphQL (for what the CLI can't do)
Some operations require direct GraphQL:
CODEBLOCK65
Projects V2 Workflow (Complete Example)
CODEBLOCK66
13. API (REST & GraphQL)
REST API
CODEBLOCK67
Placeholders
The special placeholders {owner}, {repo}, and {branch} are auto-populated from the current git directory or GH_REPO.
Pagination
CODEBLOCK68
GraphQL API
CODEBLOCK69
Common GraphQL Patterns
CODEBLOCK70
14. Extensions
CODEBLOCK71
15. Codespaces
CODEBLOCK72
16. Copilot
(Requires gh-copilot extension)
CODEBLOCK73
17. Other Commands
Browse (open in browser)
CODEBLOCK74
Status (cross-repo overview)
CODEBLOCK75
Aliases
CODEBLOCK76
SSH Keys / GPG Keys
CODEBLOCK77
Rulesets
CODEBLOCK78
Attestations
CODEBLOCK79
Org
CODEBLOCK80
18. JSON Output & Formatting
Most listing/view commands support --json, --jq, and --template flags.
Basic JSON
CODEBLOCK81
Go Template Formatting
CODEBLOCK82
Template Functions
| Function | Description |
|---|
| INLINECODE33 | Color (terminal-aware) |
| INLINECODE34 |
Force color |
|
join <sep> <list> | Join list values |
|
pluck <field> <list> | Extract field from list items |
|
tablerow <fields>... | Aligned table columns |
|
tablerender | Render accumulated tablerows |
|
timeago <time> | Relative timestamp |
|
timefmt <format> <time> | Formatted timestamp |
|
truncate <length> <input> | Truncate text |
|
hyperlink <url> <text> | Terminal hyperlink |
19. Environment Variables
| Variable | Purpose |
|---|
| INLINECODE43 / INLINECODE44 | Auth token for github.com (takes precedence over stored creds) |
| INLINECODE45 / INLINECODE46 |
Auth token for GHES |
|
GH_HOST | Default GitHub hostname |
|
GH_REPO | Default repository in
[HOST/]OWNER/REPO format |
|
GH_EDITOR | Editor for authoring text |
|
GH_BROWSER /
BROWSER | Web browser for opening links |
|
GH_PAGER /
PAGER | Terminal pager (e.g.,
less) |
|
GH_DEBUG | Enable verbose output (
1 or
api for HTTP traffic) |
|
GH_FORCE_TTY | Force terminal output (value = column count or percentage) |
|
GH_PROMPT_DISABLED | Disable interactive prompts |
|
GH_NO_UPDATE_NOTIFIER | Disable update notifications |
|
GH_CONFIG_DIR | Custom config directory |
|
NO_COLOR | Disable colored output |
|
GLAMOUR_STYLE | Markdown rendering style |
20. Advanced Patterns
Scripting Best Practices
CODEBLOCK83
Batch Operations
CODEBLOCK84
Working with Multiple Accounts
CODEBLOCK85
Rate Limiting
CODEBLOCK86
Complex API Patterns
CODEBLOCK87
21. Tips & Gotchas
Common Mistakes
- 1.
--json field names differ from API field names. For example, PR files use files (not changed_files), author uses author.login (not user.login). Always run gh <cmd> --json without arguments to see available fields.
- 2.
gh run rerun --job needs databaseId, not the URL number. Get it with:
CODEBLOCK88
- 3. Projects V2 require the
project scope. If you get permission errors:
CODEBLOCK89
- 4.
gh repo delete requires delete_repo scope:
CODEBLOCK90
- 5. Subcommand quoting in shells: PowerShell and some shells need
{owner} escaped. Use quotes: "{owner}".
When to Use gh api vs Specific Commands
| Use specific commands when... | Use gh api when... |
|---|
| The command exists and does what you need | No CLI command covers the endpoint |
| You want interactive prompts |
You need fine-grained control |
| You want pretty-printed output | You want raw JSON response |
| You're doing simple CRUD | You need GraphQL queries |
| | You need to set custom headers |
| | You need pagination control |
Performance Tips
- - Use
--limit to fetch only what you need - Use
--json with specific fields (fetches less data) - Use
--cache with gh api for frequently accessed, slowly changing data - Use
--paginate --slurp for aggregations across all pages - Set
GH_PAGER=cat to disable paging in scripts
Exit Codes
Error / failure |
| 2 | Usage error |
| 4 | Command cancelled |
| 8 | Checks pending (for
gh pr checks) |
Authentication Precedence
- 1.
GH_TOKEN / GITHUB_TOKEN environment variable - INLINECODE89 (for GHES hosts)
- Stored credentials from INLINECODE90
- INLINECODE91 file in repo (only if configured)
Useful One-Liners
CODEBLOCK91
GitHub CLI (gh) — 综合技能
版本: gh 2.66.1+
认证: gh auth login 或设置 GH_TOKEN 环境变量
不在 git 仓库目录中时,始终使用 --repo OWNER/REPO(或 -R)。
目录
- 1. 认证与配置
- 仓库
- 议题
- 拉取请求
- GitHub Actions(运行与工作流)
- 发布
- Gist
- 搜索
- 标签
- 密钥与变量
- 缓存
- Projects V2
- API(REST 与 GraphQL)
- 扩展
- Codespaces
- Copilot
- 其他命令
- JSON 输出与格式化
- 环境变量
- 高级模式
- 提示与注意事项
1. 认证与配置
认证
bash
交互式登录(基于浏览器的 OAuth)
gh auth login
使用来自标准输入的 PAT 登录
echo $MY_TOKEN | gh auth login --with-token
登录到 GitHub Enterprise
gh auth login --hostname enterprise.example.com
添加额外作用域(例如,Projects V2 的 project 作用域)
gh auth refresh -s project
添加 delete_repo 作用域
gh auth refresh -s delete_repo
检查认证状态(显示活动账户、作用域、令牌有效性)
gh auth status
gh auth status --show-token
切换活动账户(配置了多个账户时)
gh auth switch
打印活动令牌(可用于管道传输到其他工具)
gh auth token
注销
gh auth logout
各功能所需作用域:
| 功能 | 所需作用域 |
|---|
| 基本仓库/PR/议题操作 | repo |
| Gist |
gist |
| 读取组织成员身份 | read:org |
| Projects V2 | project |
| 删除仓库 | delete_repo |
| Actions 工作流 | workflow |
| 读取用户资料 | user |
配置
bash
列出所有配置
gh config list
获取/设置单个值
gh config get git_protocol # https 或 ssh
gh config set git_protocol ssh
gh config set editor code --wait
gh config set pager less -R
gh config set prompt disabled # 禁用交互式提示(适合脚本)
gh config set browser firefox
清除 CLI 缓存
gh config clear-cache
Git 凭据设置
bash
配置 git 使用 gh 进行 HTTPS 认证
gh auth setup-git
2. 仓库
创建
bash
交互式
gh repo create
公共仓库,克隆到本地
gh repo create my-project --public --clone
在组织中创建
gh repo create my-org/my-project --private
从本地目录创建
gh repo create my-project --private --source=. --remote=upstream --push
从模板创建
gh repo create my-project --template owner/template-repo --clone
带选项创建
gh repo create my-project --public --description 我的项目 \
--license mit --gitignore Node --add-readme
克隆
bash
gh repo clone owner/repo
gh repo clone owner/repo my-dir
gh repo clone owner/repo -- --depth=1 # 浅克隆
克隆自己的仓库(owner 默认为你)
gh repo clone my-repo
Fork
bash
Fork 当前仓库
gh repo fork
Fork 并克隆
gh repo fork owner/repo --clone
Fork 到组织
gh repo fork owner/repo --org my-org --fork-name new-name
仅 Fork 默认分支
gh repo fork owner/repo --default-branch-only
查看
bash
查看当前仓库(README + 描述)
gh repo view
gh repo view owner/repo
在浏览器中打开
gh repo view --web
JSON 输出
gh repo view --json name,description,stargazerCount,url
gh repo view --json name,stargazerCount --jq .stargazerCount
仓库的 JSON 字段: archivedAt, assignableUsers, codeOfConduct, createdAt, defaultBranchRef, deleteBranchOnMerge, description, diskUsage, forkCount, hasDiscussionsEnabled, hasIssuesEnabled, hasProjectsEnabled, hasWikiEnabled, homepageUrl, id, isArchived, isEmpty, isFork, isPrivate, isTemplate, languages, latestRelease, licenseInfo, name, nameWithOwner, owner, parent, primaryLanguage, pullRequests, pushedAt, sshUrl, stargazerCount, updatedAt, url, visibility, watchers
列出
bash
你的仓库
gh repo list
gh repo list --limit 100
其他用户/组织的仓库
gh repo list my-org
过滤
gh repo list --language go --visibility public
gh repo list --topic cli --no-archived
gh repo list --fork # 仅 fork
gh repo list --source # 仅非 fork
JSON 输出
gh repo list --json name,stargazerCount --jq .[] | \(.name): \(.stargazerCount) stars
编辑
bash
编辑设置
gh repo edit --description 新描述
gh repo edit --homepage https://example.com
gh repo edit --enable-issues --enable-wiki
gh repo edit --enable-projects=false
gh repo edit --default-branch main
gh repo edit --enable-auto-merge
gh repo edit --delete-branch-on-merge
gh repo edit --add-topic cli,automation
gh repo edit --remove-topic old-topic
gh repo edit --template # 使其成为模板仓库
更改可见性(危险——需要确认)
gh repo edit --visibility public --accept-visibility-change-consequences
删除 / 归档
bash
gh repo delete owner/repo --yes # 需要 delete_repo 作用域
gh repo archive owner/repo --yes
gh repo unarchive owner/repo --yes
重命名
bash
gh repo rename new-name # 重命名当前仓库
gh repo rename new-name -R owner/repo
设置默认
bash
设置此本地克隆中 gh 命令使用的远程仓库
gh repo set-default owner/repo
gh repo set-default --view # 查看当前默认
gh repo set-default --unset
同步(Fork ↔ 上游)
bash
从远程父仓库同步本地仓库
gh repo sync
同步特定分支
gh repo sync --branch v1
从其父仓库同步远程 fork
gh repo sync owner/my-fork
从特定源同步
gh repo sync owner/repo --source owner2/repo2
强制同步(硬重置)
gh repo sync --force
3. 议题
创建
bash
gh issue create --title Bug 报告 --body 此处描述
gh issue create --title Bug --label bug,urgent --assignee @me
gh issue create --title 功能 --project 路线图 --milestone v2.0
gh issue create --template Bug 报告 # 使用议题模板
gh issue create --body-file description.md # 从文件读取正文
gh issue create -R owner/repo --title Bug # 不同仓库
列出
bash
gh issue list
gh issue list --state closed
gh issue list --state all --limit 100
gh issue list --label bug --assignee @me
gh issue list --author monalisa
gh issue list --milestone v2.0
gh issue list --search error no:assignee sort:created-asc
JSON 输出
gh issue list --json number,title,labels,state --jq .[] | #\(.number) \(.title)
议题的 JSON 字段: assignees, author, body, closed