The Magic of Version Control — Part III Branching and Merging
As we continue to work on a project we might want to create a development branch. This allows us to leave the main branch as it is and work in the development branch. Once we are happy with it we can merge it back to the main branch.
Create and switch to the branch
Make sure your main branch is commited and pushed to your repository. Once you are ready to create a new branch, create it by typing:
git branch nameofyourbranch
We created the branch but we haven’t switch to it, so we type next:
git switch nameofyourbranch
With a git branch we can check that we are in the right branch. Here my branch is called dev1:
Add, commit and push it
Once we made some changes we can add, commit and push as usual, but this time to the dev1 development branch:
git add .
git commit -m "added something to dev"
git push origin dev1
If you check now in your online repository (Github or any other), you will see that you have now two branches. Your main branch remains as it was before. Your development branch has the new changes.
What about your local files. Observe the folder in the gif bellow:
Your local folder will show the status of the currently active branch. Thus it is important to be switch to the right branch before you start working on your project.
Merge it back to the main branch
What if you are happy with the development version and want to bring back the changes to your main branch?
Switch back to the main branch:
git switch main
Then we can merge the branches by typing
git merge dev1
You will now see your changes locally. But they are not applied yet on your remote repository. So we need to add:
git push origin main
Now our remote repository is updated as well.
Summary of used commands
Here a summary of the commands used in this article:
- git branch — checks which branch is active
- git branch nameofbranch — creates the nameofbranch branch
- git push origin nameofbranch — pushes your local branch to the remote repository
- git switch whatever — switches to the whatever branchg
- git merge nameofthebranch — you need to be in your main (or whatever branch you want to add your development branch to)
If you missed the first part of this series:
Part I The Magic of Version Control with Git and Github
Part II The Magic of Version Control — Part II Frequent Git Commands