Simple Git Tutorial: Branching and Merging
Git's powerful branching and merging capabilities can help you deal with parallel collaborative development processes. Let's take a look.
So far, we've been working on a single default branch created by Git. The name of this branch is main
. (It used to be master
. See github/renaming: Guidance for changing the default branch name for GitHub repositories) Our every commit becomes a new node on this branch.
When we want to add a new feature, but aren't sure if the new feature is good enough to use, the natural thought is that we want to branch out based on our current location and do our new feature development and experimentation on the new branch. If it's good, merge it into the main branch. Otherwise discard it.
Branching
The basic commands for working on local branches are listed below:
1 | # lists all the local branches |
All of the above commands work on the local branch(es). Then let's take a look at the remote branch(es).
To list all the local and remote branches, run:
1 | git branch --all |
When you clone a repo from the Internet, you may find that there is a main
branch and an origin/main
branch. Here, main
is a local branch, and origin/main
is a remote branch (where origin
means a remote server called origin
and main
means a branch of the same name on that remote server).
In this case, the local branch main
and the remote branch origin/main
are related in some way, called tracking. The local branch is called the tracking branch. The corresponding branch on the remote server is called the upstream branch. Usually, the tracking branch shares a name with its upstream branch (e.g., the upstream branch of a local branch feature
is origin/feature
), but that's not a requirement.
For example, the commands below create a new local branch feature
and its upstream branch origin/feature
:
1 | git checkout -b feature |
Run the command below to show the connection:
1 | git branch -vv |
More commands may be helpful:
1 | # sets up a new tracking |
Merging
To merge the other branch to this one, run:
1 | git merge <branch_name> |
If your current branch is master
, this command merge <branch_name>
to master
.
To show all the branches that have/haven't been merged to this branch, run:
1 | git branch --merged |