Git tip: create a Git upstream alias

Here’s a simple git alias to make your life a little easier if you work with feature branches:

  $ git config --global alias.upstream '!git push -u origin HEAD'

Now running git upstream will:

  1. push the branch to the remote origin
  2. set the local branch to track the remote branch so that future git push and git pulls will automatically happen against the remote

When is this alias useful?

This alias will be useful if you’ve ever tried to push up a new feature branch and this has happened:

  $ git push
  fatal: The current branch feature-x has no upstream branch.
  To push the current branch and set the remote as upstream, use

      git push --set-upstream origin feature-x

Git is telling us that it doesn’t know where this branch should be pushed to because (at least by default) it doesn’t make assumptions about where a given branch should be pushed to or pulled from.

Helpfully, Git has told us the command we probably want to run to push to the remote origin with the same branch name and set that as the upstream branch to track.

Our new alias essentially does the same thing, but instead of giving a specific branch name we use HEAD, which is a reference to the tip of the current branch and means the command will work without having to explicitly use the name of the branch:

  $ git upstream
  Enumerating objects: 6, done.
  Counting objects: 100% (6/6), done.
  Delta compression using up to 4 threads
  Compressing objects: 100% (4/4), done.
  Writing objects: 100% (4/4), 1.74 KiB | 297.00 KiB/s, done.
  Total 4 (delta 2), reused 0 (delta 0)
  remote: Resolving deltas: 100% (2/2), completed with 2 local objects.
   * [new branch]      feature-x -> feature-x
   Branch 'feature-x' set up to track remote branch 'feature-x' from 'origin'.

Alternatively, do it with a config setting

As of Git version 2.37.0, it’s now possible to set a config setting that will make git push automatically push to the remote and set the tracking branch:

 git config --global --add --bool push.autoSetupRemote true

I personally still prefer to use the git upstream alias. Maybe because it feels more deliberate? Or perhaps it’s just part of my muscle memory…

I’ve got a bunch more Git-related tips in the pipeline. If you’re looking to power up your Git skills and understanding, sign up to my mailing list below!

Want more juicy Git tips like this straight to your inbox?

You'll get an email whenever I have a fresh insight or tip to share. Zero spam, and you can unsubscribe whenever you like with a single click.

More articles on Git

Authored by Published by