Skip to content

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

  1. Automate PR creation and merge with gh command
  2. Automated PR review integrated with CI/CD pipelines
  3. 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

StepContentSuccess Metric
1gh initial setup and authenticationAuthentication confirmed via gh auth status
2Implement PR auto-creation scriptPR created with single command
3CI/CD integration and review automationPR 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

SymptomCauseImmediate Action
gh: command not foundCLI not installedInstall via brew install gh or apt/yum
authentication requiredToken expiredRe-authenticate with gh auth refresh
PR creation failedBranch protection settingsCreate 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 {}
### Automated PR Review Comments
gh pr review --comment --body "LGTM! CI passed."