Sub topic 11
Merging from the command line with gh
The gh command-line tool can merge a pull request without opening the browser. It calls the same GitHub merge operation as the web buttons, so the result on the base branch is identical. This chapter covers the command's flags and how it interacts with repository settings, auto-merge, and local branches.
This chapter assumes you have:
- Installed
ghand rungh auth login. - Read the earlier chapters on the three merge methods and on the repository settings that allow or forbid them.
- Used
git log --graphto inspect history.
What `gh pr merge` does
gh pr merge asks GitHub to merge a pull request using one of the three methods. GitHub does the merge on its servers. Your local clone is not involved, except for the optional cleanup described below.
The general form is:
gh pr merge [<number> | <url> | <branch>] [flags]The argument selects the pull request. If you leave it out, gh uses the pull request for the branch you currently have checked out.
| Flag | Method | Same as the web button |
|---|---|---|
| `--merge` or `-m` | Merge commit | Create a merge commit |
| `--squash` or `-s` | Squash | Squash and merge |
| `--rebase` or `-r` | Rebase | Rebase and merge |
Choosing the method
Pick the method with a flag. This example merges pull request 123 with each of the three methods in turn. In practice you would run only one of them, because a pull request can be merged once.
gh pr merge 123 --merge
gh pr merge 123 --squash --delete-branch
gh pr merge 123 --rebaseIf you run gh pr merge 123 in a terminal with no method flag, gh prompts you. It asks which method to use and whether to delete the branch. Only the methods the repository allows appear in the prompt.
In a script or CI job there is no terminal to prompt in, so gh requires an explicit method flag. A command without one fails instead of waiting for input. This is the main reason to always pass a flag in automation.
gh pr merge 123 --squashIf you request a method the repository has disabled, GitHub rejects the request. You see an error such as "Merge commits are not allowed on this repository". The fix is a different flag or a change to the repository settings. Check the settings chapter for where those toggles live.
Setting the commit message
For merge commits and squash merges, you can override the message that GitHub generates:
gh pr merge 123 --squash \
--subject "Add export to CSV (#123)" \
--body "Adds a CSV exporter and its tests."--subject(-t) sets the commit title.--body(-b) sets the commit body.--body-file(-F) reads the body from a file. Use-to read from standard input.--author-email(-A) sets the email address used for the merge commit's author.
These flags have no effect on a rebase merge. A rebase merge does not create a new commit message. It replays the existing commits, each keeping its own message.
Checking the state before you merge
Merging can fail or be blocked because of reviews, checks, or conflicts. Look at the state first:
gh pr view 123 --json mergeable,mergeStateStatus,reviewDecision
gh pr checks 123mergeable reports MERGEABLE, CONFLICTING, or UNKNOWN. UNKNOWN often means GitHub has not finished computing it yet, so run the command again after a few seconds. mergeStateStatus gives more detail, such as CLEAN, BLOCKED, BEHIND, or DIRTY. reviewDecision reports APPROVED, CHANGES_REQUESTED, or REVIEW_REQUIRED when the repository requires reviews.
If you run gh pr checks 123 --watch, gh keeps polling until the checks finish. This is a convenient step before the merge in a script.
Cleaning up branches with `--delete-branch`
--delete-branch (-d) removes the pull request's head branch after the merge. It affects two places:
- The remote branch on GitHub is deleted.
- If you have that branch checked out locally,
ghswitches your clone to the default branch and deletes the local branch.
The second step is the part that surprises people. Your working tree changes branch as a side effect of the command. Commit or stash any uncommitted work on that branch first. If you are not in a clone of the repository and pass the pull request number with --repo, gh only touches the remote branch.
gh pr merge 123 --squash --delete-branch --repo octo-org/octo-repoIf the repository has the setting "Automatically delete head branches" turned on, GitHub deletes the remote branch anyway, and the flag only matters for the local cleanup.
The local cleanup does not update your main branch. Run git pull on it afterwards to bring the new commit down.
git switch main
git pull --ff-only
git log --oneline --graph --decorate -5Waiting for requirements with `--auto`
Often a pull request cannot be merged yet because required checks are still running or a review is missing. --auto tells GitHub to merge automatically as soon as every requirement is met:
gh pr merge 123 --squash --autoThe command returns immediately. GitHub performs the merge later, using the method you chose. Two conditions apply:
- The repository must have "Allow auto-merge" turned on in its settings.
- The base branch must have branch protection or a ruleset with at least one requirement, such as required status checks or required approvals. With no requirements, there is nothing to wait for, so the pull request would simply merge immediately.
Pushing new commits to the branch does not cancel auto-merge by itself, but a new review that requests changes, or failing checks, keeps the pull request from merging. To cancel it, run:
gh pr merge 123 --disable-autoIf the base branch uses a merge queue, gh pr merge adds the pull request to the queue instead of merging it directly. The queue's own settings then decide the method.
Bypassing requirements with `--admin`
--admin merges a pull request even when branch protection requirements are not satisfied. It works only if your account has permission to bypass them.
gh pr merge 123 --squash --adminUse it for emergencies, not routine work. It skips the safeguards the team set up, and the bypass is visible in the repository's audit trail.
Guarding against a moving branch
Between the moment you review a pull request and the moment you merge it, someone could push a new commit. --match-head-commit makes the merge conditional on the head being exactly the commit you reviewed:
gh pr merge 123 --squash --match-head-commit 3f2a9c1If the branch tip differs, the merge fails and nothing is merged. This is useful in scripts that approve and merge in the same run.
Scripting a safe merge
The pieces above combine into a short script that merges only when the pull request is ready:
#!/usr/bin/env bash
set -euo pipefail
pr="$1"
state=$(gh pr view "$pr" --json mergeable --jq '.mergeable')
if [ "$state" != "MERGEABLE" ]; then
echo "PR $pr is $state, not merging" >&2
exit 1
fi
head=$(gh pr view "$pr" --json headRefOid --jq '.headRefOid')
gh pr merge "$pr" --squash --delete-branch --match-head-commit "$head"The script refuses to merge a pull request with conflicts or an unknown state. It also pins the merge to the head commit it just read.
How the pieces fit together
The diagram shows what gh pr merge decides, in order, when you run it.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Command fails in CI with a message about choosing a method | No method flag and no terminal | Add `--merge`, `--squash`, or `--rebase` |
| "Merge commits are not allowed" or similar | The method is disabled in repository settings | Use an allowed method, or change the settings |
| "Pull request is not mergeable" | Conflicts, failing checks, or missing approvals | Resolve the cause, or use `--auto` to wait |
| `--auto` reports that auto-merge is not allowed | Setting off, or no branch protection requirements | Enable "Allow auto-merge" and add requirements |
| Local branch changed unexpectedly | `--delete-branch` switched you to the default branch | Stash or commit first |
| Merge fails with a head commit mismatch | Someone pushed after you read the head | Review the new commit, then retry |
Exercise
A teammate's script runs gh pr merge 57 --delete-branch in a CI job and fails every time. Name the problem and write the corrected command so that the pull request is squash merged, merges as soon as required checks pass, and the branch is deleted.
Show answer
The CI job has no terminal, so gh cannot prompt for a merge method, and no method flag was given. Add a method flag. Because the checks may still be running, add --auto: gh pr merge 57 --squash --auto --delete-branch. This also requires "Allow auto-merge" in the repository settings and at least one requirement on the base branch.
Exercise
You run gh pr merge 88 --merge on a repository whose base branch has "Require linear history" enabled. Does adding --admin make the command succeed? What should you use instead?
Show answer
No. The linear history rule forbids merge commits on the base branch, and --admin only bypasses unmet requirements such as approvals and checks, not that rule. Use --squash or --rebase, whichever the repository allows.