Just made a mistake to push commits to a wrong remote branch. Below is the detail.
- Need to create a new branch
br-x
, which needs to be based on the newest remotedev
branch. - Run
git fetch
to get newest change from the remote. - Run
git checkout -b br-x origin/dev
to create branchbr-x
. - Change and commit files in branch
br-x
. - Run
git push origin -u br-x
to push commits to the remote.
In step 3, the origin/dev
is used to as the “start-point” of the new br-x
branch. As per git branch --help
,
When a local branch is started off a remote-tracking branch, Git sets up the branch (specifically the
branch.<name>.remote
andbranch.<name>.merge
configuration entries) so that git pull will appropriately merge from the remote-tracking branch. This behavior may be changed via the global branch.autoSetupMerge configuration flag.
In other words, the git checkout -b br-x origin/dev
not only create a new br-x
branch, but also let the br-x
track
the remote dev
branch. As a result, in step 5, the git push origin -u br-x
doesn’t push commits into a same-name remote branch.
However, it pushes commits into the remote dev
branch, which the local br-x
is tracking since its creation.
The remote dev
branch is accidentally modified. 😞
To avoid it, one method is use the local dev
branch as the “start-point” in step 3. Consider the local dev
may be behind
the remote dev
. You may have to switch to the local dev
and git pull
to update it first.
Another method is using --no-track
option, i.e. git checkout -b --no-track br-x origin/dev
.
A more thorough method is using git config --global branch.autoSetupMerge false
to change the default behavior of Git.
When branch.autoSetupMerge
is false
, when create a branch, Git will not setup its tracking branch even if the “start-point” is a remote-tracking branch.
From more details search “branch.autoSetupMerge” in git config --help
.
For what is “remote-tracking” branch, check this link. Simply put,
Remote-tracking branch names take the form
<remote>/<branch>
.