David Y.
—How can I create a new branch in my Git repository based on an existing branch?
When creating a new branch, Git will automatically use the currently checked-out branch as a base. Let’s say our repository has two branches: main
and dev
. We want to create a feature
branch based on the dev
branch.
If we’re already on the dev
branch, we can go ahead and create a new branch with the following git checkout
command:
git checkout -b feature
The -b
flag creates the new branch feature
, which is now our repository’s current branch.
If we’re on the main
branch, we will need to modify our command to specify dev
as the base for our new branch:
git checkout -b feature dev
Regardless of the branch we started on, our repository will now be on the feature
branch, which will have an identical history to the dev
branch. We can now do our work on this branch and commit to it without affecting dev
.
If we want to push this branch to a remote, we can use the following git push
command:
git push -u origin feature
The -u
flag ensures that feature
is created in our remote repository and linked to our local feature
branch.
Once we’ve completed the work we need to do on the feature
branch, we can switch back to dev
and merge it back in with these commands:
git checkout dev git merge feature
If no new commits have been made to dev
since the creation of feature
, Git will add all of the commits from feature
to dev
(this is called fast-forwarding). If commits have been made, git merge
will create a new merge commit joining the branches – in some instances, we may need to resolve merge conflicts first.
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.