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:
- push the branch to the remote origin
- set the local branch to track the remote branch so that future
git push
andgit pull
s 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!