DEV Community

Cover image for Automating PR comments with Github CLI
Daniel Handloser
Daniel Handloser

Posted on

Automating PR comments with Github CLI

As an engineer, my day-to-day involves reviewing pull requests (PRs). Oftentimes these are small changes and I would review around 30 PRs per week.

For me to approve a request, I need to trigger different checks by commenting on the PR. If you're going through the same struggle every day, here is how to automate this process with Github CLI.


On macOS: make sure you have 'brew' installed and run

brew install gh
Enter fullscreen mode Exit fullscreen mode

Bash script

We're going to write a small bash script that fetches all open PRs and creates a comment.

On your console cd to the directory of the repository that the pull requests are in. gh pr list will allow us to find all open PRs.

Depending on your needs you can find different flags in the documentation. For my work I usually look at all PRs with a certain title, the query is gh pr list -S "<YOUR SEARCH>". To make a comment, we need the PRs ID, which is called number in Github. We can extract that by telling gh to output a JSON.

With the command-line JSON processor jq we're getting the number of the PR:

gh pr list -S "<YOUR SEARCH>" --json "number" --jq '.[].number'
Enter fullscreen mode Exit fullscreen mode

Looping over the results we can add a comment to every PR in our list. This is the final snippet:

for prNumber in $(gh pr list -S "<YOUR SEARCH>" --json "number" --jq '.[].number'); do
    echo "Triggering PR no. $prNumber\n"
    gh pr comment $prNumber --body "<YOUR MESSAGE>"
Enter fullscreen mode Exit fullscreen mode

And we're done. This will leave a comment on all the PRs from your search query.

Photo by Anna Shvets from Pexels

Discussion (0)