How to checkout to a specific pull request with git

An issue I sometimes encounter is, when someone makes a pull request to one of my public repos. I want to see these changes locally first, before blindly merging the changes. Turns out that it's pretty easy to checkout to a specific pull request.

git fetch origin pull/<#>/head:<local_branch_name>

An example: You want to checkout to pull request #23.

git fetch origin pull/23/head:pr/23

This will fetch the pull request and create a local branch named "local-23". All you have to do then is checkout to that branch.

git checkout pr/23

Going further, we can create a git alias, to make the command a little nicer.

git config --global "!f() { git fetch origin pull/$1/head:pr/$1 && git checkout pr/$1;  }; f"

This will create a local branch named "pr/<#>" and checkout to that branch. Usage:

git pr <#>
⟵ back