Mastering Git: Branching and Merging – Part 2

RMAG news

Introduction

In Part 1, we covered the fundamental concepts and commands needed to get started with Git. Now, we’ll dive deeper into one of Git’s most powerful features—branching and merging. This functionality not only enhances collaborative efforts but also significantly improves the development process.

What are Branches?

In Git, branches are effectively pointers to snapshots of your changes. When you want to add a new feature or fix a bug, you create a new branch to isolate your changes. This means you can work on new features without disturbing the main part of the project, often referred to as the master or main branch.

Creating a Branch

To create a branch, use the command:

git branch new-feature

This command creates a new branch called new-feature. To switch to this branch and start working on it:

git checkout new-feature

Alternatively, you can create and switch to the branch in one command:

git checkout -b new-feature

Making Changes and Committing

While on your new branch, any changes you make will only affect that branch. You can make changes, stage them, and commit them as follows:

git add .
git commit -m “Add new feature”

These changes will not impact the main branch until they are explicitly merged back.

Merging Branches

Once your feature is complete and tested, you can merge it back into the main branch:

git checkout main
git merge new-feature

This command switches you back to the main branch and then merges the changes from new-feature into main.

Resolving Conflicts

Sometimes, Git can’t automatically merge changes, resulting in conflicts. You’ll need to manually resolve these conflicts. Git will mark the files that have conflicts, and you must choose which changes to keep.

Deleting a Branch

After merging, if you no longer need the branch, you can delete it:

git branch -d new-feature

This removes the branch locally. If you’ve pushed the branch to a remote repository, you might also want to delete it there:

git push origin –delete new-feature

Conclusion

Understanding branching and merging is crucial for managing larger projects and collaborating with others. In Part 3, we will explore more advanced Git features like rebasing and working with remote repositories.

Stay tuned to become a Git expert!

Leave a Reply

Your email address will not be published. Required fields are marked *