Skip to content

Instantly share code, notes, and snippets.

@spmason
Last active May 8, 2026 11:02
Show Gist options
  • Select an option

  • Save spmason/7889198 to your computer and use it in GitHub Desktop.

Select an option

Save spmason/7889198 to your computer and use it in GitHub Desktop.
GitHub "open PR" script. Add somewhere in your path, then opening a PR is as easy as typing `pr` on the branch you want to open a PR for
#!/usr/bin/env bash
# GitHub "Open Pull Request" script
#
# Add somewhere in your path, then opening a PR is as easy as typing `pr` while you're
# on the branch you want to open a Pull Request for
#
# NOTES:
# - Uses the `gh` tool: https://cli.github.com/
# - Assumes that the upstream repository is called 'origin' and your fork is named after your github username
# (this is how `gh clone` and then `gh fork` should set things up)
PUSH_ARGS=""
SHOW_BROWSER=0
LOCAL_BRANCH=$(git name-rev --name-only HEAD)
USERNAME=$(gh api user --jq .login)
while test $# -gt 0
do
case "$1" in
--force) PUSH_ARGS="--force-with-lease"
;;
-f) PUSH_ARGS="--force-with-lease"
;;
--browser) SHOW_BROWSER=1
;;
-b) SHOW_BROWSER=1
;;
--no-browser) SHOW_BROWSER=0
;;
-n) SHOW_BROWSER=0
;;
esac
shift
done
# Find the current remote for the local branch, or use the username if no remote is found
REMOTE=$(git config branch."${LOCAL_BRANCH}".remote || echo "${USERNAME}")
if ! git remote | grep "$USERNAME" 1> /dev/null; then
echo "No remote $USERNAME found. Pushing to origin"
REMOTE=origin
fi
git push --set-upstream ${REMOTE} ${LOCAL_BRANCH} ${PUSH_ARGS}
if ! gh pr view ${REMOTE}:${LOCAL_BRANCH} --json url --jq .url &> /dev/null; then
if [[ $SHOW_BROWSER == 1 ]]; then
# Open browser to create new PR
HEAD="${REMOTE}:${LOCAL_BRANCH}"
if [[ "${REMOTE}" = "origin" ]]; then
echo "Remote is ${REMOTE}"
HEAD="${LOCAL_BRANCH}"
fi
gh pr create --web --head "$HEAD" ${CREATE_ARGS}
fi
elif [[ $SHOW_BROWSER == 1 ]]; then
# Show existing PR
gh pr view ${REMOTE}:${LOCAL_BRANCH} --web
else
# Just output the PR URL
gh pr view ${REMOTE}:${LOCAL_BRANCH} --json url --jq .url
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment