Working with branches

Suppose we got a bug report. To fix this bug we should first create a new branch. This way any changes that we do to our code can be tested before we merge them into production. To create a new branch we run

git branch new_branch_name

If we run git branch, Git will return a list of the branches our project has. The branch we are currently in will have an asterisk next to its name.


To switch branches we run

git switch target_branch_name

If at any point in time we wish to rename a branch we use

git branch -m current_name new_name
Working with branches 1
Working with branches 2

Now that we are in the new branch, we can work on fixing the bug. Once we are done, we need to stage and commit our changes.


Suppose we've done all that. If we take a look at the log now we'll see that our bugfix branch is ahead of the master branch. If we switch back to the master branch, we'll see that the bug is still there. We still need to merge our branches.

Once we are done with a branch, we should delete it. To do so we run

git branch -d branch_name

Keep in mind that if the changes that you did in that branch have not been merged into the master branch, Git will complain about this action. This is to protect you from accidentally deleting work you still need. To override this protection we use

git branch -D branch_name
Working with branches 3