How to Avoid Having to Do “Git Branch --set-upstream”, and Instead Default to Automatically Setup Remote Tracking?
To avoid having to manually set the upstream branch for each new branch you create and instead default to automatically set up remote tracking, you can configure Git to always set up remote tracking by default when creating new branches.
Configure Git to Auto-Track Remote Branches
Global Configuration:
You can set this behavior globally so that it applies to all repositories on your machine:
git config --global push.default current git config --global branch.autoSetupMerge always
- `git config --global push.default current`: This sets the default push behavior to push the current branch to its upstream counterpart.
- `git config --global branch.autoSetupMerge always`: This configures Git to always set up a tracking relationship when creating a new branch with `git checkout -b` or `git switch -c`.
Repository-Specific Configuration:
If you want to set this behavior for a specific repository only, run the commands without the
--global
flag inside your repository:git config push.default current git config branch.autoSetupMerge always
Automatically Set Upstream Branch with git checkout
or git switch
With the configuration set, new branches created with git checkout -b
or git switch -c
will automatically set up tracking branches. For example:
# Using git checkout
git checkout -b new-branch
# Or using git switch
git switch -c new-branch
When you push the new branch to the remote for the first time, use:
git push -u origin new-branch
After the initial push, subsequent pushes and pulls will track the remote branch automatically.
Example Workflow
Create and switch to a new branch:
git checkout -b feature-xyz
Make some changes and commit them:
git add . git commit -m "Add new feature"
Push the new branch to the remote repository:
git push -u origin feature-xyz
- The `u` flag here sets the upstream tracking reference for the new branch.
After these steps, your branch feature-xyz
will be automatically set to track origin/feature-xyz
, and you won't need to run git branch --set-upstream
manually. Future pushes and pulls will be simpler and will automatically interact with the remote branch.
Make your mark
Join the writer's program
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.
Write for usBuild on top of Better Stack
Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.
community@betterstack.comor submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github