Lesson 4
Git Branching
In this lesson, we will dive into Git branching, a powerful feature that allows you to work on multiple versions of your project simultaneously. We will cover creating and switching branches, merging branches, and resolving merge conflicts.
Objectives
- Understand the concept of branches in Git
- Learn how to create and switch branches
- Learn how to merge branches
- Understand how to resolve merge conflicts
Understanding branches
In Git, a branch is a separate line of development within a repository. It allows you to work on different features or bug fixes simultaneously without affecting the main branch (usually called "master"
or "main"
). When a feature or bug fix is complete, you can merge the changes back into the main branch.
Creating and switching branches
To create a new branch, use the git checkout -b
command followed by the branch name. This will create a new branch and switch to it. To switch between branches, use the git checkout
command followed by the branch name.
Merging branches
To merge changes from one branch into another, first switch to the target branch using git checkout
. Then, use the git merge
command followed by the source branch name. Git will automatically merge the changes if there are no conflicts.
Resolving merge conflicts
Merge conflicts occur when the same lines of code have been changed in both branches. Git cannot automatically merge these changes, so you must manually resolve the conflicts. Git will mark the conflicting lines in the affected files, and you can edit the files to keep the desired changes. After resolving the conflicts, commit the changes to complete the merge.
Exercises
Create and switch branches
Create a new branch called "feature" in your local repository using the git checkout -b
command. Then, switch back to the main branch using the git checkout
command.
Resolve a merge conflict
- Create a new branch called "conflict" and switch to it.
- In the "conflict" branch, open a file and make some changes to it. Commit the changes.
- Switch back to the main branch and make changes to the same lines of the same file. Commit the changes.
- Attempt to merge the "conflict" branch into the main branch using the
git merge
command. Git will report a merge conflict. - Open the affected file and look for the conflict markers (
<<<<<<<
,=======
, and>>>>>>>
). Edit the file to keep the desired changes and remove the conflict markers. - Commit the changes to complete the merge.