Sub topic 10
Using gh in scripts and automation
This chapter assumes you can run gh interactively, know how --json and --jq work, and are comfortable writing short bash scripts. It covers what changes when gh runs without a person at the keyboard: credentials, repository selection, prompts, and error handling.
What changes in a script
Interactive gh relies on three things that a script or CI job may not have:
- A login stored by
gh auth login. - A local clone that tells
ghwhich repository you mean. - A terminal where
ghcan ask you questions.
A script replaces each one explicitly. Credentials come from an environment variable, the repository comes from a variable or a flag, and every command gets all its inputs from flags.
Credentials and repository selection
gh reads GH_TOKEN (or GITHUB_TOKEN) and uses it instead of any stored login. GH_REPO selects the repository in OWNER/REPO form, so no local clone is needed.
export GH_TOKEN="$MY_TOKEN"
export GH_REPO="cli/cli"
gh pr list --state open --json number --jq '.[].number' | while read -r n; do
echo "Open PR: $n"
doneHere --json number asks for one field, and --jq '.[].number' prints one number per line. That plain output is what makes the while read loop work.
Keeping commands non-interactive
Commands such as gh issue create prompt for missing values when they run in a terminal. In a script, supply every value with flags so nothing waits for input:
gh issue create \
--title "Nightly check failed" \
--body "See the latest workflow run." \
--label bugWhen output is piped or redirected, gh detects that it is not talking to a terminal. It drops colors and decorations and prints tab-separated text, which is easier to parse. For stable parsing, still prefer --json and --jq over scraping the default text, because the default layout is meant for people and can change.
Exit codes and failure
gh returns a non-zero exit status when a command fails. Use that status instead of checking output text.
#!/usr/bin/env bash
set -euo pipefail
if ! gh pr checks --watch; then
echo "Checks failed or could not be read" >&2
exit 1
fiset -euo pipefail stops the script on the first error, on unset variables, and on failures inside pipelines. Without pipefail, a failing gh at the start of a pipe is hidden by the success of the last command.
gh pr checks has more than one failure state, such as failed checks versus checks still pending. If your logic depends on the difference, read the exit code in a variable and test its value rather than treating every non-zero result the same.
Falling back to the API
When no gh subcommand covers what you need, gh api works with the same authentication and GH_REPO conventions. The {owner} and {repo} placeholders fill in from the current repository, and --paginate follows every page:
gh api repos/{owner}/{repo}/issues --paginate --jq '.[].title'Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `gh` asks to log in in CI | `GH_TOKEN` is not exported | Export it, and check the secret name in your CI config |
| "not a git repository" | No clone and no `GH_REPO` | Set `GH_REPO=OWNER/REPO` or pass `--repo` |
| Script hangs | A command is waiting for a prompt | Add the missing flags, such as `--title` and `--body` |
| HTTP 403 or 404 on a private repository | Token lacks the needed scope or access | Issue a token with the right permissions |
| Loop runs on partial data | Output has more than one page | Use `--paginate` with `gh api`, or raise `--limit` on list commands |
Exercise
A CI job runs gh pr list --json number --jq '.[].number' and fails with a message that it cannot determine the repository. The job has no checkout step. Which two environment variables would you set, and why?
Show answer
Set GHTOKEN so gh authenticates without a stored login, and set GHREPO to OWNER/REPO so gh knows which repository to query without a local clone.
Exercise
Why is gh pr list --json number --jq '.[].number' a safer input for a loop than parsing the default gh pr list output?
Show answer
The JSON fields and the jq filter are explicit and stable, so the loop gets exactly one number per line. The default output is formatted for people and its layout can change.