When I first started using git, I was told by another team member to always push using
git push -u origin MYBRANCH
because it would prevent me accidentally pushing code to the wrong branch. I didn't fully understand and today tried to understand what happens that means.
I created a local repo and provide my exact commands so you could copy/paste this to reproduce what I've done.
In this test I have a local (on disk) repo and two branches:
git branch
main
* feature/fixthis
I'm on the feature/fixthis
branch and run:
git push -u origin main
# NOTE: the current branch is feature/fixthis
Did I just accidentally push my feature branch onto main?
My Solution (figure it out myself using local test)
To test this out myself, I did the following. The commands are written in such a way that you can copy/past to a UNIX bash shell to reproduce a local git repo and create the exact scenario I'm asking about.
# Step 1: Create local repo
mkdir so-test; cd so-test; git init --bare local-git-repo.git
# Step 2: git clone local (empty repo).
git clone ./local-git-repo.git test-this
# Step 3: Add a Readme.md file, commit and push the change
cd test-this; echo hi > README.md; git add README.md; git commit -m "initial commit"; git push -u origin main
# Step 4: Check the branch feature/fixit.
git co -b feature/fixit
# Step 5: Make change and accidentally push it to main.
echo In feature/fixit >> README.md; git add -u .; git commit -m "change on feature/fixit";
# Step 6: Do the push from the feature/fixit branch to main
git push -u origin main
Did the command git push -u origin main
accidentally update the main branch?
When I look at the logs I can't figure out what happened to the last push, it doesn't appear to have updated the origin/main branch because I don't see the origin/feature/fixit tag (on any commit).
git log
commit 1bba12ad200080cb0a59aa0e2fb518a1e284b135 (HEAD -> feature/fixit)
Author: me@example.com
Date: Thu Apr 7 14:25:19 2022 +0000
change on feature/fixit
commit dcf8098bda7c937c80bc60ee974ac6eb9a895ced (origin/main, main)
Author: me@example.com
Date: Thu Apr 7 14:20:06 2022 +0000
initial commit
Searching for answers
Search [git] git push -u origin - around 20,000 results... Hum... that's not going to work, let me add another question to the category. :-)
What exactly does the "u" do? "git push -u origin master" vs "git push origin master" - Good answer with lots of good technical stuff. It might answer my question but if it does I didn't see it.
Many others