When working with GitHub repositories, developers often need to perform actions after a pull request reaches a particular state. For example, a deployment script might need to wait until a pull request is merged, a CI pipeline might need to check whether reviews are completed, or an automation script might need to continue after all required checks pass.

A common approach is to repeatedly call the GitHub API and check whether the pull request status has changed. Although this works, it creates unnecessary API requests and makes automation scripts more complicated.

GitHub CLI provides a simpler way to handle this situation through its gh pr checks and gh pr view commands, along with the gh pr checks --watch option for monitoring check progress.

Developers can also use GitHub webhooks and event-driven workflows when they need to react automatically to pull request activities.

In this article, we will explore how to use GitHub CLI to monitor pull request activity, wait for CI checks, automate workflows, and avoid common mistakes when building GitHub automation scripts.

Why Waiting for Pull Request Events Matters

A pull request is not always ready for the next development step immediately after it is created.

It might need to pass several checks, including:

  • Unit tests.
  • Integration tests.
  • Code quality checks.
  • Security scanning.
  • Build validation.
  • Required reviewer approvals.

Consider a deployment script that should continue only after all required CI checks have completed successfully.

Without an appropriate waiting mechanism, the script might start deployment while some checks are still running.

Developers sometimes solve this by repeatedly requesting pull request information from the GitHub API.

For example:

Bash
while true; do
    STATUS=$(gh pr view 125 --json state \
        --jq '.state')

    if [ "$STATUS" = "MERGED" ]; then
        echo "Pull request merged"
        break
    fi

    sleep 10
done

This script checks the pull request state every 10 seconds.

Although the implementation is simple, it continuously makes requests even when nothing has changed.

GitHub CLI provides more convenient commands for monitoring pull request checks without manually writing the entire polling mechanism.

Understanding GitHub CLI

GitHub CLI, commonly called gh, is a command-line tool that allows developers to interact with GitHub repositories directly from a terminal.

It supports operations such as:

  • Creating and viewing pull requests.
  • Managing issues.
  • Reviewing pull request checks.
  • Triggering GitHub Actions workflows.
  • Viewing workflow runs.
  • Managing releases.
  • Interacting with GitHub API endpoints.

For developers who regularly work with GitHub, the CLI makes it easier to automate repository operations without writing a separate API client.

Installing GitHub CLI

On macOS, developers can install GitHub CLI using Homebrew:

Bash
brew install gh

On Windows, use Windows Package Manager:

PowerShell
winget install --id GitHub.cli

On Linux, use the installation package appropriate for your distribution.

After installation, verify that the CLI is available:

Bash
gh --version

Authenticating With GitHub

Before using commands that access private repositories or perform authenticated operations, authenticate with GitHub.

Run:

Bash
gh auth login

Follow the interactive instructions to select GitHub.com or the relevant GitHub Enterprise host and complete authentication.

Verify the current authentication status:

Bash
gh auth status

For automated environments, GitHub CLI can also use an appropriately scoped GH_TOKEN environment variable.

Avoid placing personal access tokens directly inside scripts or committing them to repositories.

Monitoring Pull Request Checks With GitHub CLI

One of the most useful commands for this workflow is:

Bash
gh pr checks

It displays the status of checks associated with a pull request.

For example:

Bash
gh pr checks 125

This command displays information about the checks associated with pull request 125.

Depending on the repository configuration, the results may include:

CheckStatus
BuildPass
Unit TestsPass
Integration TestsPending
Security ScanPass

When some checks are still running, developers can monitor their progress using the watch option.

Bash
gh pr checks 125 --watch

The --watch option waits for the checks to complete and displays status updates as they change.

This is useful when a developer wants to monitor CI execution from the terminal without repeatedly running the same command.

However, it is important to understand what this command monitors.

It waits for the associated checks to complete. It does not wait for the pull request itself to be merged or guarantee that the branch is ready for deployment.

Waiting for Pull Request Checks Before Continuing

Consider a development workflow where a script should continue only after the pull request checks have completed.

A simple shell script can use GitHub CLI:

Bash
#!/bin/bash

PR_NUMBER=125

echo "Waiting for pull request checks..."

gh pr checks "$PR_NUMBER" --watch

if [ $? -eq 0 ]; then
    echo "Pull request checks completed successfully."
else
    echo "Pull request checks did not complete successfully."
    exit 1
fi

echo "Continuing the next operation..."

This script monitors the checks and uses the command's exit status to determine whether it should continue.

A more concise implementation is:

Bash
#!/bin/bash

PR_NUMBER=125

if gh pr checks "$PR_NUMBER" --watch; then
    echo "All monitored checks completed successfully."
    ./next-step.sh
else
    echo "Pull request checks failed or could not be completed."
    exit 1
fi

The second version uses shell conditional execution, which makes the script easier to read.

For production automation, remember that a successful command exit does not necessarily mean that every repository merge requirement has been satisfied. Review the repository's required checks, branch protection rules, and merge requirements separately.

Using the Current Pull Request Instead of a Fixed Number

Developers do not always know the pull request number in advance.

For scripts executed from inside a GitHub repository, GitHub CLI can identify the current pull request.

For example:

Bash
gh pr view --json number

To extract the pull request number:

Bash
PR_NUMBER=$(gh pr view --json number \
    --jq '.number')

The script can then monitor its checks:

Bash
#!/bin/bash

PR_NUMBER=$(gh pr view --json number --jq '.number')

if [ -z "$PR_NUMBER" ]; then
    echo "No pull request found for the current branch."
    exit 1
fi

echo "Monitoring pull request: $PR_NUMBER"

gh pr checks "$PR_NUMBER" --watch

This approach is useful when developers work with multiple feature branches and want to reuse the same automation script.

Monitoring Pull Request Events With GitHub Actions

GitHub CLI is useful for terminal-based monitoring, but some automation tasks are better handled directly through GitHub Actions.

GitHub Actions supports pull request event triggers.

For example, a workflow can execute whenever a pull request is opened, updated, or reopened.

YAML
name: Pull Request Validation

on:
  pull_request:
    types:
      - opened
      - synchronize
      - reopened

jobs:
  validate:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Run tests
        run: |
          echo "Running pull request validation"

The pull_request event starts the workflow when one of the configured activities occurs.

The synchronize activity is particularly useful because it triggers when new commits are pushed to an existing pull request.

This allows validation to run automatically whenever the pull request changes.

For production workflows, use appropriate action versions and review permissions, especially when workflows run against code from external contributors.

Waiting for a Pull Request to Be Merged

Monitoring CI checks and waiting for a pull request to be merged are two different requirements.

If the automation needs to wait for a merge event, GitHub Actions provides the closed pull request activity.

For example:

YAML
name: Post Merge Automation

on:
  pull_request:
    types:
      - closed

jobs:
  after-merge:
    if: github.event.pull_request.merged == true

    runs-on: ubuntu-latest

    steps:
      - name: Confirm merge
        run: |
          echo "Pull request was merged successfully."

The workflow runs when a pull request is closed, but the if condition ensures that the job executes only when the pull request was actually merged.

This distinction is important because closing a pull request does not necessarily mean that it was merged.

Using GitHub CLI in CI/CD Pipelines

GitHub CLI can also be integrated into deployment and release scripts.

For example, a workflow might need to inspect the checks associated with a pull request before executing a later operation.

A GitHub Actions workflow can install and authenticate GitHub CLI using the automatically provided token:

YAML
name: PR Check Monitor

on:
  workflow_dispatch:

permissions:
  contents: read
  pull-requests: read
  checks: read

jobs:
  monitor:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Monitor pull request checks
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          gh pr checks 125 --watch

The GH_TOKEN environment variable provides authentication to GitHub CLI.

The permissions section follows the principle of least privilege by granting only the permissions required by this example.

In a real workflow, the pull request number should come from the event payload, workflow input, or another validated source rather than being hardcoded.

Also, avoid creating workflows that wait indefinitely for checks that cannot run or depend on the current workflow itself. Such dependencies can create unnecessary waiting or workflow deadlocks.

GitHub CLI vs GitHub Webhooks vs GitHub Actions

Developers have several options for responding to pull request activity.

FeatureGitHub CLIGitHub WebhooksGitHub Actions
Primary purposeTerminal-based GitHub operationsDeliver event notificationsAutomate repository workflows
ExecutionLocal or CI environmentExternal application or serviceGitHub-hosted or self-hosted runner
Pull request monitoringYesYesYes
Custom automationShell scriptsBackend applicationsWorkflow jobs
Infrastructure managementUsually minimalRequires webhook receiverManaged by GitHub or runner infrastructure
Best suited forDeveloper scripts and CI tasksExternal integrationsRepository automation

The right choice depends on where the automation needs to run.

Use GitHub CLI when a developer or script needs to monitor repository activity from a terminal.

Use GitHub Actions when automation should run automatically in response to repository events.

Use webhooks when an external application needs to receive GitHub event notifications.

Best Practices for Reliable Pull Request Automation

Use Explicit Pull Request Identifiers

Avoid depending on the current branch when scripts might execute from different repository contexts.

Pass the pull request number explicitly when possible.

Handle Command Failures

Network problems, authentication issues, missing permissions, and failed checks can all affect CLI commands.

Use proper error handling and exit codes so that downstream operations do not run unexpectedly.

Avoid Infinite Waiting

Set reasonable time limits for automation tasks.

A script that waits forever can occupy CI runners and delay other workflows.

Use Least-Privilege Permissions

Grant only the repository permissions needed for the operation.

Avoid using highly privileged tokens for simple monitoring tasks.

Keep Deployment Separate From Check Monitoring

Passing CI checks does not automatically mean that a deployment is safe.

Include any required approval, environment protection, security validation, and deployment conditions in the release workflow.

Prefer Event-Driven Automation When Possible

If an external service needs to react to pull request changes, use webhooks instead of repeatedly requesting repository status.

This reduces unnecessary API traffic and provides a cleaner integration model.

Common Mistakes Developers Should Avoid

MistakeWhy it causes problemsBetter approach
Confusing completed checks with merged pull requestsThe pull request may still be openMonitor merge state separately
Running repeated API requests manuallyCreates unnecessary API trafficUse gh pr checks --watch
Ignoring exit codesScripts may continue after failed checksUse conditional execution
Using hardcoded pull request numbersMakes automation difficult to reuseRead validated workflow inputs
Giving workflows excessive permissionsIncreases security riskApply least-privilege permissions
Waiting indefinitelyCan occupy CI resourcesImplement timeouts
Assuming every check is requiredOptional checks may behave differentlyReview branch protection requirements

Troubleshooting Common Problems

GitHub CLI Cannot Find the Pull Request

Make sure the current branch is associated with an existing pull request.

You can inspect the pull request using:

Bash
gh pr view

If you are working outside the repository context, specify the repository using the --repo option.

Authentication Failed

Check the authentication status:

Bash
gh auth status

For automated environments, verify that the GH_TOKEN environment variable is available and has the necessary permissions.

Pull Request Checks Are Not Updating

Verify that the CI workflows are running and that the checks are associated with the correct commit.

Also confirm that the repository has not restricted the required permissions.

The Script Continues After a Failed Check

Use the command inside an if statement and stop execution when the command returns a nonzero exit status.

Also distinguish between a command failure and a successful command that reports an unsuccessful check state.

Summary

Waiting for pull request activity is a common requirement in modern development and CI/CD workflows. Repeatedly checking GitHub API responses manually can make automation unnecessarily complicated.

GitHub CLI provides convenient commands such as gh pr checks and gh pr checks --watch to monitor CI check progress directly from the terminal.

Developers can combine these commands with shell scripts to automate subsequent operations. For workflows that need to respond to pull request creation, updates, or merging, GitHub Actions and webhooks provide event-driven alternatives.

The important part is selecting the right mechanism for the task. Use GitHub CLI for terminal-based monitoring, GitHub Actions for repository automation, and webhooks for external integrations.

With proper error handling, authentication, permissions, and timeout management, teams can build more reliable pull request automation without maintaining unnecessary polling scripts.