Create Pull Requests and then Merge Multiple GitHub Repos from the Command Line

Kareemy
ITNEXT
Published in
2 min readSep 2, 2020

--

The problem I’m trying to solve: how to create PRs for multiple GitHub repositories and then merge those repos via CLI—without using the GitHub UI!

I decided to take advantage of GitHub’s Hub, which GitHub describes as “an extension to command-line git” to create the pull requests, and then use GitHub’s API to merge those PRs. I work on a Mac, so I used Brew to install Hub: brew install hub

To solve the problem, I developed this Bash script to create the Pull Requests (Note that anything in less than/greater than brackets <> needs to be altered to match your setup):

#!/bin/bashdate=$(date +%F-%H)
curdir=$(pwd)
echo '#!/bin/bash' >> merge_all-${date}.sh
echo 'source .env' >> merge_all-${date}.sh
for path in */<path_goes_here>*
do
[[ ! -d "$path" ]] && continue
echo "$path"
cd "$path"
pr=$(hub pull-request --base <OWNER>:<base_branch> --head <branch_with_changes> -m "helpful message goes here")
echo "$pr"
repo=$(echo "$pr" | awk -F "/" {'print $5'})
pull_number=$(echo "$pr" | awk -F "/" {'print $7'})
cd $curdir
echo "echo \"$repo\"" >> merge_all-${date}.sh
echo "curl -s -X PUT \
-H \"Authorization: token \$token\" \
https://api.github.com/repos/<OWNER>/$repo/pulls/$pull_number/merge" >> merge_all-${date}.sh
done

This script lives at the root of a directory that contains several repos. It loops through the directories using the $path variable, creates the PR, then adds that PR to a new script that is generated in the root directory. That generated script will be called merge_all-<Date_of_Execution>.sh and will contain several curl commands that use the GitHub API to then merge the PRs. I separated Pull Requesting and Merging into distinct scripts in order to allow time for peer reviewing.

Note that the GitHub API requires an Authorization token, which you can set up following GitHub’s documentation. That token will need to be in a .envfile that also lives at the root directory. Here’s what that .env file looks like:

token=“<GitHub_Token_Goes_Here>”

If everything goes well after running the pull request creation script, you should have a script that looks somewhat like this:

If this helps you out at all, then congrats on all the time you’ll save not having to manually merge individual repos in the GitHub GUI 🙂

--

--