In this article, I show you how you can switch git branches while working on git. These are very often you have to do while working on git.
Suppose you have two branches one for development where as a developer you have been working and one is the main branch where everyone in a team commits the changes.
So let’s start first create one dev branch.
Create a branch in git
In Git, you can create a new branch using the git branch command. Below is the syntax to create a branch in git
git branch <branch name>
The below command creates a branch named “dev”
git branch dev
Switch git branches
The new “dev” branch is created but it does not switch to it. To switch to the new branch and start working on it you can use the git checkout command.
git checkout dev
You can also create and switch to a new branch immediately using below one command-
git checkout –b <branch name>
So, you can switch between branches using the git checkout command. When you switch to a branch, Git updates your working directory to match the contents of that branch. Any changes you have made to the files in your working directory will be stashed or discarded, depending on whether they have been committed or not.
Always keep in mind before switching to another branch you should make sure that your current branch is up to date, you can use the git pull command to achieve that.
Also, if you want to switch to a new branch and start working on it, it’s a good practice to create a new branch using git branch <branch-name> and then switch to it using git checkout <branch-name>.
Below is another useful command that shows all the branches that exist locally and remotely in the repo.
Git brand –a
It’s important to note that switching branches can potentially cause conflicts if you have made changes to files that have also been modified in the branch you are switching to. In this case, you will need to resolve the conflicts before you can switch to the new branch. Git will notify you of any conflicts and guide you on how to resolve them.
This is how you can switch git branches now you are able to switch branches using the git checkout command. This is helpful when you working on git.