GIT - 5.5 Examples of a simple branch

Branches are one of the most powerful features of Git. They let you work on a change in isolation, without affecting the main line of development. This lesson walks through a complete, simple branch example: creating a branch, working on it, and merging it back.

Creating and switching to a branch

A branch in Git is simply a movable pointer to a commit. You create one with git branch and move onto it with git checkout:

git branch nouvelle-fonctionnalite   # create the branch
git checkout nouvelle-fonctionnalite # switch to it

Modern Git also offers a shortcut that does both at once:

git checkout -b nouvelle-fonctionnalite

From this point, every commit you make is recorded on the branch nouvelle-fonctionnalite, while the main branch stays untouched.

Working on the branch

You work exactly as usual: edit your files, stage them, and commit. The commits accumulate on your branch only:

git add fichier.txt
git commit -m "Add new feature"

You can check which branch you are on and see the full list at any time with git branch. The current branch is marked with an asterisk.

Merging the branch back

Once the work is finished, you bring the changes back into the main line. You first switch to main, then merge the branch into it:

git checkout main
git merge nouvelle-fonctionnalite

When main has not changed in the meantime, Git performs a fast-forward merge: it simply moves the main pointer forward to your branch's last commit. Finally, once the branch has been merged and is no longer needed, you can delete it cleanly with git branch -d nouvelle-fonctionnalite.