GitHub CLI Reference
Purpose
Reference GitHub CLI installation, authentication, and commands for the current
authorized operation. Use the installed binary discovered with command -v gh;
run Step 0 in the current shell before the examples, which use the resolved GH path.
Activation cues
- Requests to use GitHub CLI or
ghcommands - Questions about GitHub API, PRs, issues, workflows
- Pull request operations (list, view, create, merge)
- GitHub repository queries
- Workflow run checks
- GitHub API operations
- Authentication errors or "command not found" errors
Installation (One-Time Setup)
Step 0: Check if Already Installed
GH="$(command -v gh || true)"
if [ -z "$GH" ] && [ -x "$HOME/.local/bin/gh" ]; then
GH="$HOME/.local/bin/gh"
fi
if [ -n "$GH" ]; then
echo "gh CLI already installed: $GH"
"$GH" --version
else
echo "gh CLI not found; installation is needed"
fi
Step 1: Install Only When Missing
If GH is empty, inspect the current platform and use its supported installation
method from the GitHub CLI installation instructions.
Complete installation within the task's existing authority, then rerun Step 0.
Preserve an existing working binary; a missing ~/.local/bin/gh alone does not
mean GitHub CLI is absent.
Step 2: Verify Installation
"$GH" --version
Expected output: the installed GitHub CLI version.
Step 3: Test Authentication
"$GH" auth status
Expected output: ✓ Logged in to github.com account <username> (GITHUB_TOKEN)
Note: GitHub CLI automatically uses the GITHUB_TOKEN environment variable - no prefix needed!
Critical Usage Rules
✅ ALWAYS Do This:
- Use the installed binary: resolve it with
command -v gh; use~/.local/bin/ghwhen installed there - GITHUB_TOKEN automatic: No prefix needed - gh automatically uses environment variable
- Specify repo: Add
--repo "$REPO"for clarity, withREPOset once per shell:
REPO="${GITHUB_REPOSITORY:-$("$GH" repo view --json nameWithOwner -q .nameWithOwner)}"
(gh repo view resolves the repository of the current checkout; if REPO is empty, set GITHUB_REPOSITORY=owner/repo)
❌ NEVER Do This:
- Don't reinstall over a working binary: inspect the current PATH and platform first
- Don't use /tmp: Install to a supported location (system package manager or ~/.local/bin) to comply with TEMPORARY FILE ISOLATION policy; never install into /tmp
- Don't add redundant prefix:
GITHUB_TOKEN=$GITHUB_TOKENis unnecessary
Command Reference
Authentication & Status
Check auth status
"$GH" auth status
Check API rate limit
"$GH" api rate_limit --jq '.rate | {limit: .limit, remaining: .remaining}'
Repository Operations
View repository info
"$GH" repo view "$REPO"
View repository info (JSON)
"$GH" repo view "$REPO" --json name,owner,isPrivate,defaultBranchRef,description
List branches
"$GH" api "repos/$REPO/branches" --jq '.[0:10] | .[] | {name: .name, protected: .protected}'
Pull Request Operations
List open PRs
"$GH" pr list --repo "$REPO" --state open --limit 10
List all PRs (including closed)
"$GH" pr list --repo "$REPO" --state all --limit 20
View specific PR
"$GH" pr view '<PR_NUMBER>' --repo "$REPO"
View PR with JSON output
"$GH" pr view '<PR_NUMBER>' --repo "$REPO" --json number,title,state,author,createdAt,body
View PR checks/status
"$GH" pr checks '<PR_NUMBER>' --repo "$REPO"
Create PR
"$GH" pr create --repo "$REPO" --title "PR Title" --body "PR Description"
Create PR (interactive)
"$GH" pr create --repo "$REPO" --fill
Merge PR
"$GH" pr merge '<PR_NUMBER>' --repo "$REPO" --squash
View PR comments
"$GH" api "repos/$REPO/pulls/<PR_NUMBER>/comments"
Issue Operations
List issues
"$GH" issue list --repo "$REPO" --limit 10
List open issues with labels
"$GH" issue list --repo "$REPO" --state open --label bug --limit 10
View specific issue
"$GH" issue view '<ISSUE_NUMBER>' --repo "$REPO"
Create issue
"$GH" issue create --repo "$REPO" --title "Issue Title" --body "Issue Description"
Workflow Operations
List workflows
"$GH" workflow list --repo "$REPO"
List workflow runs
"$GH" run list --repo "$REPO" --limit 10
List workflow runs for specific workflow
"$GH" run list --repo "$REPO" --workflow "Workflow Name" --limit 10
View workflow run details
"$GH" run view '<RUN_ID>' --repo "$REPO"
Watch workflow run
"$GH" run watch '<RUN_ID>' --repo "$REPO"
Label Operations
List labels
"$GH" label list --repo "$REPO"
Create label
"$GH" label create "label-name" --repo "$REPO" --description "Label description" --color "ff0000"
GitHub API Direct Access
Get user info
"$GH" api user --jq '.login'
Get latest commit on main
"$GH" api "repos/$REPO/commits/main" --jq '{sha: .sha[0:7], author: .commit.author.name, message: .commit.message | split("\n")[0]}'
Get repository collaborators
"$GH" api "repos/$REPO/collaborators"
Get repository topics
"$GH" api "repos/$REPO/topics"
Troubleshooting
Error: "command not found: gh"
Cause: The binary is absent from the current PATH.
Solution: Inspect command -v gh and the known installation path; install for the current platform only if needed.
Error: "You are not logged into any GitHub hosts"
Cause: No usable authentication is available to this invocation.
Solution: Inspect gh auth status. For an environment-token setup, check
test -n "${GITHUB_TOKEN:-}" && echo "GITHUB_TOKEN is set". Never print the token.
Error: "HTTP 404: Not Found"
Cause: Missing --repo flag or incorrect repo name
Solution: Add --repo "$REPO" to the command and check that REPO is the intended owner/repo
Error: "Resource not accessible by integration"
Cause: Token lacks required permissions
Solution: Verify token scopes with gh auth status, ensure token has repo scope
Binary not found: "gh"
Cause: gh CLI not installed or not on PATH
Solution: Follow Step 0 to discover the binary or install via the platform's supported method (e.g. brew install gh on macOS or ~/.local/bin/gh on Linux)
Advanced Patterns
Check if gh is installed
if command -v gh >/dev/null 2>&1 || [ -x "$HOME/.local/bin/gh" ]; then
echo "gh CLI is installed"
else
echo "gh CLI not installed, run installation steps"
fi
Get PR number from current branch
PR_NUMBER=$("$GH" pr list --repo "$REPO" --head $(git branch --show-current) --json number --jq '.[0].number')
echo "Current branch PR: #$PR_NUMBER"
Check if PR exists for current branch
PR_EXISTS=$("$GH" pr list --repo "$REPO" --head $(git branch --show-current) --json number --jq 'length')
if [ "$PR_EXISTS" -gt 0 ]; then
echo "PR exists for current branch"
else
echo "No PR for current branch"
fi
Get PR status with detailed info
"$GH" pr view '<PR_NUMBER>' --repo "$REPO" --json number,title,state,isDraft,mergeable,reviewDecision,statusCheckRollup
Environment Variables
GITHUB_TOKEN
- Purpose: Authentication token for GitHub API
- Set automatically: Available as environment variable
- Usage: GitHub CLI automatically uses this environment variable (no manual prefix needed)
- Scopes: Inspect the current account's permissions; do not assume administrative access.
Integration with Other Tools
Use with jq for JSON parsing
"$GH" pr list --repo "$REPO" --json number,title --jq '.[] | "\(.number): \(.title)"'
Use in scripts
#!/bin/bash
set -e
# Define gh command
GH="$(command -v gh || true)"
if [ -z "$GH" ] && [ -x "$HOME/.local/bin/gh" ]; then
GH="$HOME/.local/bin/gh"
fi
[ -n "$GH" ] || { echo "Run the installation steps first" >&2; exit 1; }
REPO="${GITHUB_REPOSITORY:-$("$GH" repo view --json nameWithOwner -q .nameWithOwner 2>/dev/null || true)}"
[ -n "$REPO" ] || { echo "GITHUB_REPOSITORY not configured: export GITHUB_REPOSITORY=owner/repo" >&2; exit 1; }
# Use in script
"$GH" pr list --repo $REPO --limit 5
Use with grep for filtering
"$GH" pr list --repo "$REPO" | grep "OPEN"
Best Practices
- Resolve the installed binary: Prefer
command -v gh, then the executable~/.local/bin/ghfallback. - GITHUB_TOKEN automatic: gh CLI automatically uses environment variable (no prefix needed)
- Always specify --repo: Makes commands explicit and prevents errors
- Use --json with --jq: For parsing specific fields from responses
- Check installation first: Verify gh binary exists before using
- Use --limit: Prevent overwhelming output for list commands
- Store in variable: Define
GHvariable in scripts for reusability
Quick Copy-Paste Commands
# Set up gh command variable for easy reuse
GH="$(command -v gh || true)"
if [ -z "$GH" ] && [ -x "$HOME/.local/bin/gh" ]; then
GH="$HOME/.local/bin/gh"
fi
[ -n "$GH" ] || { echo "Run the installation steps first" >&2; exit 1; }
REPO="${GITHUB_REPOSITORY:-$("$GH" repo view --json nameWithOwner -q .nameWithOwner 2>/dev/null || true)}"
[ -n "$REPO" ] || { echo "GITHUB_REPOSITORY not configured: export GITHUB_REPOSITORY=owner/repo" >&2; exit 1; }
# Now you can use it like this:
"$GH" pr list --repo $REPO
"$GH" issue list --repo $REPO
"$GH" workflow list --repo $REPO
Related Skills
pr-workflow-manager.md- PR creation and management best practicescloud-ops-credential-guard.md- Token and credential management
Reporting Expectations
When using gh CLI, always:
- Confirm gh binary exists before running commands
- Include the command without expanded credential values or token prefixes
- Show relevant actual output with credentials redacted
- Report diagnostic errors with credentials redacted
- Verify authentication status if commands fail
Before declaring GitHub/API work blocked — source of truth
Origin: ~/.claude/CLAUDE.md § GitHub API fallback before blocking
(compressed there to a pointer 2026-09-06; this section is the full policy).
Never report GitHub/API work as blocked without first, independently, trying
both REST and GraphQL where the operation permits either (REST and GraphQL
operate under separate quota buckets). Independent fallback attempts are permitted
only for read-only or idempotent operations. When an uncertain response occurs
on a non-idempotent mutation (such as creating a comment, creating a release, or
modifying state), the client must read back the current state or check idempotency
before any retry attempt; never retry a mutation blindly to avoid creating duplicate
comments, releases, or side effects. Public REST endpoints may be tried unauthenticated
when the authenticated quota is exhausted; unauthenticated and authenticated paths can
have different read/write permissions and rate limits, so a 403 on one is not proof
the other is unavailable. Use bounded probes (a fixed small number of attempts, not an
open retry loop) and respect any circuit breaker already in place. Never loop
indefinitely on a failing call, and never bypass authentication or safety checks to
force a call through. Human merge authority and approval gates remain strictly preserved;
automated fallbacks must never merge pull requests without explicit authorization.