How to Implement Pull Request Automation with GitHub CLI in 5 Minutes¶
Target Audience
- Intermediate: Engineers who use GitHub daily and are comfortable with CLI operations
Key Points¶
- Automate PR creation and merge with gh command
- Automated PR review integrated with CI/CD pipelines
- Create team-specific workflow templates
Why This Matters Now¶
Manual PR creation is a development flow bottleneck. The average developer spends 20 minutes daily on PR-related tasks, which can be reduced by 80% using gh CLI. Particularly effective for multi-repository management and regular release tasks.
Solution Steps Overview¶
| Step | Content | Success Metric |
|---|---|---|
| 1 | gh initial setup and authentication | Authentication confirmed via gh auth status |
| 2 | Implement PR auto-creation script | PR created with single command |
| 3 | CI/CD integration and review automation | PR checks run automatically |
Step 1: gh Initial Setup and Authentication¶
Initial setup of GitHub CLI and authentication token configuration. OAuth authentication is recommended over Personal Access Token. Required scopes are repo, workflow, read:org.
# Authentication setup (interactive)
gh auth login
# Non-interactive (for CI/CD)
echo $GITHUB_TOKEN | gh auth login --with-token
Step 2: Implement PR Auto-Creation Script¶
Implement routine PR creation with a one-liner. Pre-define title, body, reviewers, and labels to standardize development flow.
#!/bin/bash
# pr-create.sh
gh pr create \
--title "feat: $1" \
--body-file .github/pr_template.md \
--reviewer @team/backend \
--label "enhancement,review-needed" \
--milestone "v2.0"
Step 3: CI/CD Integration and Review Automation¶
Combine GitHub Actions with gh to implement auto-merge based on PR check results. Execute merge when tests pass + approval criteria met.
# .github/workflows/auto-merge.yml
- name: Auto-merge Dependabot PRs
if: github.actor == 'dependabot[bot]'
run: |
gh pr review --approve "$PR_URL"
gh pr merge --auto --squash "$PR_URL"
env:
PR_URL: ${{ github.event.pull_request.html_url }}
Common Pitfalls and Solutions¶
| Symptom | Cause | Immediate Action |
|---|---|---|
gh: command not found | CLI not installed | Install via brew install gh or apt/yum |
authentication required | Token expired | Re-authenticate with gh auth refresh |
| PR creation failed | Branch protection settings | Create draft with --draft option |
Advanced Configuration
### Custom PR Template Usage Place standard format in `.github/pull_request_template.md` and reference with `--body-file`. Standardize checklists, impact scope, and test items. ### Batch Operations Across Repositories# List repositories in repos.txt
cat repos.txt | xargs -I {} gh pr list --repo {}
gh pr review --comment --body "LGTM! CI passed."