Fetching remote branch with git

Git may sometimes be confusing. While basic commands are quite straight forward, some other still basic but less used are not so. I have been googling about how to fetch and pull a branch from a remote repository, if the branch does not yet exist in the local repository. While I have found many questions, I could not find the right answer. So I went exploring in the git documentation and discovered, I should do this more often.

While I did first git fetch origin it’s the git checkout -b branchname remote/branchname command that did the trick. This is from the docs:

To prepare for working on <branch>, switch to it by updating the index and the files in the working tree, and by pointing HEAD at the branch. Local modifications to the files in the working tree are kept, so that they can be committed to the <branch>.

If <branch> is not found but there does exist a tracking branch in exactly one remote (call it <remote>) with a matching name, treat as equivalent to

$ git checkout -b <branch> --track <remote>/<branch>

Hope this helps other people.