Working with branches in Git is one of the most powerful ways to manage your code. In this tutorial, we’ll walk through how to create a repository, add branches, make commits, and finally merge multiple branches into your main branch.
ðŠī Step 1: Create a New Git Repository
Let’s start by initializing a new Git repository in your local project folder:
git init
This creates a hidden .git folder — the home of all your version history.
Next, connect your local repository to a remote one (for example, on GitHub):
git remote add origin https://github.com/unicornautomata/test_app.git
Now fetch existing data (if any) and pull the latest changes from the remote repository:
git fetch origin
git pull origin main
his ensures your local main branch is up to date.
ðŋ Step 2: Create and Work on Branch AA
Let’s create a new branch named AA and switch to it:
git checkout -b AA
Now, add a new file to this branch:
git add git_tut.txt
git commit -m "Add git_tut.txt file"
git push -u origin AA
This pushes branch AA to your GitHub repository.
ðģ Step 3: Create and Work on Branch BB
Go back to the main branch, then create another branch named BB:
git checkout main
git checkout -b BB
Now add two files — New.txt and git_tut.txt — then commit and push your changes:
git add New.txt git_tut.txt
git commit -m "Add New.txt and update git_tut.txt"
git push -u origin BB
ðž Step 4: Create a Merge Branch (CC)
Now, we’ll merge both AA and BB into a new branch called CC.
Switch back to main and create CC:
git checkout main
git checkout -b CC
Then merge the other two branches:
git merge AA
git merge BB
If everything merges cleanly, push CC to the remote repository:
git push -u origin CC
If a conflict occurs — meaning there’s a change in branch BB that overlaps with the current version of the file in CC — simply open the file in your code editor (in my case, Atom). You’ll see sections labeled something like “your changes” and “their changes”, often with buttons to choose between them.
If you want to keep only one version, click the corresponding button. If you prefer to keep both changes, just remove the conflict markers (your changes and their changes labels), adjust the content as needed, and save the file.
Finally, push branch CC to the remote repository:
git push -u origin CC
ðŧ Step 5: Merge Everything Back to Main
Finally, let’s bring all your updates back into the main branch.
git checkout main
git merge CC
git push -u origin main
Your main branch now contains all the changes from AA, BB, and CC.
ð Step 6: Verify Everything
You can check your branches and commit history to verify your merges:
git log --oneline --graph --all
This shows a visual representation of your branches and merge history.
ð§Đ Summary
Here’s what we accomplished:
-
Initialized a Git repository and connected it to GitHub
-
Created branches (
AA,BB,CC) -
Added and committed changes on each branch
-
Merged all branches cleanly back into
main
You’ve just completed a practical hands-on Git merging tutorial! ð