Wes Bragavim-wes
Platform Engineering

How to push a new branch and create a pull-request in one command

February 20, 2023
tree-branches

Are you tired of manually creating pull requests on GitHub every time you make a change to your repository? With this Bash script, you can automate the process and save yourself some time. In this tutorial, we will walk you through how to build a Bash script that creates a pull request against the appropriate branch on your GitHub repository.

Show me

gif example pull-request

Step 1: Create a New Bash Script

To get started, open your terminal and create a new Bash script using your favorite text editor. For this tutorial, we'll call our script create_pr.sh. To create the file, run the following command:

touch create_pr.sh

Step 2: Write the Script

Next, open the file in your preferred text editor:

nvim create_pr.sh
#!/bin/bash

# Current branch name
BRANCH=$(git symbolic-ref --short HEAD)

# Which branch the current branch derives from
PARENT_BRANCH=$(git merge-base --fork-point master $BRANCH)

# If the parent branch is "main", create a pull request against "main"
if [[ "$PARENT_BRANCH" == "main" ]]; then
  TARGET_BRANCH="main"
else
  TARGET_BRANCH="$PARENT_BRANCH"
fi

# Push the current branch upstream
git push -u origin head

# Get the URL of the remote repository
REMOTE_URL=$(git config --get remote.origin.url)

# Extract the username and repository name from the remote URL
USERNAME=$(echo "$REMOTE_URL" | awk -F':' '{print $2}' | sed 's/\/.*//')
REPO=$(echo "$REMOTE_URL" | awk -F'/' '{print $2}')

link="https://github.com/$USERNAME/$REPO/pull/new/$BRANCH"
# Open the pull request page in a web browser
open $link

Step 3: Save and Test the Script

Once you've copied and pasted the code into the create_pr.sh file, save the file and exit your text editor. Make sure the file is executable by running the following command:

chmod +x create_pr.sh

To test the script, create a new branch in the current directory, add and commit and execute the script by running:

bash ./create_pr.sh

If everything works correctly, the script will generate a link to the pull request page for the new branch and open it in a web browser.

Bonus sauce

Without having to think about a good alias for this, here is one

alias gpr="bash ~/scripts/create_pr.sh"

Conclusion

In this tutorial, I showed you how to build a Bash script that automates the process of creating a pull request on a GitHub repository. With a little bit of practice, you can customize this script to fit your specific needs and create a pull request workflow that works best for you. Let me know if this was helpful to you.