In Git, a branch represents a way to provide an isolated copy of the current code. The code in the branch can be modified without affecting the original code and, when it is ready, the changes can be moved back into the original code. Branches also make it much easier to undo changes.
Creating a Branch
The basic syntax for creating a branch in Git is this:
Using this command from
<current-branch> will create a new branch called
<branch-name> based off of the code that is currently in
Deleting a Branch
The basic syntax for removing a branch in Git is this:
As long as the branch has no uncommitted code, this command will remove the branch entirely. It will no longer be available to check out, and the changed code will be unrecoverable.
Moving Between Branches
The basic syntax for moving between branches in Git is this:
This will change the active branch to the one named
<branch-name>. Any editing done this point will be to the copy of the code within
<branch-name> rather than the previous branch.
The basic syntax for moving code from one branch into another in Git is this:
This will merge the code from
<branch-name> to the currently checked out branch.
When working with code, a programmer will often want to work on a specific feature. They will create a branch off of the main one, and code within it. Once they are happy with the feature and are certain that it is ready to be added back to the main branch they will merge it from the feature branch into the main one. Finally, they will clean up their repository by deleting the feature branch.
First, we branch off of the
main branch and check out the new one:
When our code is ready, and fully committed to the new branch: