I am relatively new to using Git for team projects and I’m confused about the syntax. Sometimes I see people just type git push, and other times they use git push origin. Does git push origin always target the main branch, or does it depend on which branch I have checked out locally? Also, if I have multiple remotes configured, how does Git decide where the data goes if I omit the word 'origin'? I want to avoid accidentally pushing my code to the wrong place.
3 answers
The main difference lies in explicitness and default configurations. git push origin explicitly tells Git to push your current branch to the remote named 'origin'. In contrast, git push relies on your "upstream" tracking information. If you previously ran git push -u origin main, Git remembers that 'origin' is the default target for your local 'main' branch, allowing you to simply type git push in the future. In professional Software Development environments, it is often safer to use the explicit git push origin [branch-name] to ensure you are pushing the correct local branch to the intended remote destination, especially when working with forks or multiple upstream repositories.
What happens if I have a remote named 'upstream' and a remote named 'origin'? If I just type git push, does it try to push to both, or does it fail if I haven't set a default for the specific branch I'm on?
Technically, git push without arguments follows the push.default setting in your Git config. In newer versions, it usually defaults to 'simple', pushing only the current branch to its upstream.
Matthew is right about the config. I actually changed my global config to 'current' so that git push always assumes I want to push my current branch to a remote branch of the same name. It saves a lot of keystrokes!
Great question, Steven! If you haven't set an upstream tracking branch, Git will actually show an error message and suggest the command to set it. It won't push to both automatically. It only pushes to the one linked to your current branch. This is why many seniors prefer being explicit—it prevents the "fatal: The current branch has no upstream branch" error from interrupting your flow during a deployment.