#11 Branches
branch, checkout, merge
What is a branch?
A branch is like a parallel timeline for your code. It allows you to work on a feature or a fix without touching the main code.
By default, Git creates a branch called main. When you create a new branch, you start from a copy of the current state and can make independent changes.
git branch -- List and create branches
To see existing branches, use git branch. The asterisk * indicates the active branch:
$ git branch
* mainTo create a new branch:
$ git branch new-feature
$ git branch
* main
new-featureNote: git branch name creates the branch but does not switch you to it.
git checkout -- Switch branches
To switch to another branch, use git checkout:
$ git checkout new-feature
Switched to branch 'new-feature'The shortcut git checkout -b lets you create and switch in a single command:
$ git checkout -b fix-bug
Switched to a new branch 'fix-bug'Working on a branch
Once on your branch, you work normally: edit files, run git add and git commit. These commits only affect the current branch.
$ git checkout -b my-feature
# ... edit files ...
$ git add .
$ git commit -m "Add my new feature"git merge -- Merge branches
When your work on a branch is done, you merge it into the main branch. First switch to the target branch, then merge:
$ git checkout main
Switched to branch 'main'
$ git merge new-feature
Updating a1b2c3d..d4e5f6g
Fast-forward
app.js | 15 +++++++++++++++
1 file changed, 15 insertions(+)Here, Git performs a fast-forward: it simply moves the main pointer forward because there is no divergence. If both branches have evolved differently, Git creates a merge commit.
Summary
git branch # List branches
git branch name # Create a branch
git checkout name # Switch to a branch
git checkout -b name # Create + switch
git merge name # Merge a branchYour turn
Try creating branches, switching between them, and merging them in the terminal below.