Set Upstream Branch for Git

Update 8/17/2022: I just learned about the new git setting: push.autoSetupRemote — I learned it from here, and so can you!

You’ve seen it many times:

There is no tracking information for the current branch.
Please specify which branch you want to rebase against.
See git-pull(1) for details.

    git pull <remote> <branch>

If you wish to set tracking information for this branch you can do so with:

    git branch --set-upstream-to=origin/<branch> master

So what do you do? You go to the mouse, swipe over the command to select it, copy it (if your terminal doesn’t do that automatically), paste it as a new command, fiddle with it a bit for accuracy, and press Enter. Voila. Tracking information easily set.

Fiddlesticks.

What if I gave you a better way? Enter Shell Functions.

We’re going to create a zsh shell function that will allow you to type:

  • gsut to set the upstream tracking branch to the same name as the current branch
  • gsut <name> to set the upstream tracking branch to the branch named name

If you haven’t deciphered it yet, “gsut” stands for Git Set Upstream To. I was going to name this function “gsu” but I have that aliased to git submodule update.

For this function, we must retrieve the name of the current branch. You have several ways to do this. We’ll set the result to a local variable called “current”:

local current
current="$(git rev-parse --abbrev-ref HEAD)"

If we’re passed a parameter, we’ll use that for the name of the upstream branch. Otherwise, we’ll use the name of the current branch:

  local upstream
  if [[ $# -eq 0 ]]; then
    upstream=$current
  else
    upstream=$1
  fi

All that remains is to run the git command. Our entire function looks like this:

# git branch --set-upstream-to
function gsut() {
  local current
  current="$(git rev-parse --abbrev-ref HEAD)"
  
  local upstream
  if [[ $# -eq 0 ]]; then
    upstream=$current
  else
    upstream=$1
  fi

  git branch --set-upstream-to="origin/$upstream" "$current"
}

Never type more than necessary. Or use the mouse if you can avoid it.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.