Git from the Terminal

Lesson 2 of 5

The Nature of Branching

Concept:

A branch is not a copy of your code. It is a tiny file containing a single 40-character hash pointing to a commit. Creating a branch is instant because Git copies nothing β€” it just writes a new pointer. HEAD is another pointer that tells Git which branch you're currently on. Merging brings one branch's commits into another β€” always switch to the target branch first.
Socrates: Tell me β€” when you create a branch in your desktop tool, what do you believe happens?
Student: Git makes a copy of all my files on the new branch, doesn't it?
Socrates: A reasonable belief. And how long does it take?
Student: It's instant. Even on large projects.
Socrates: Instant! And yet you say Git copies all your files? Tell me β€” if I asked you to copy a thousand files, would that be instant?
Student: No, that would take time. So... Git isn't copying files?
Socrates: It is not. A branch is a tiny file β€” forty characters long β€” containing the hash of a commit. Nothing more. When you 'create a branch', Git writes one small file. That is why it is instant.
Student: Just a pointer? Then what is HEAD?
Socrates: Another pointer! HEAD points to the branch you are currently on. When you switch branches, only HEAD changes β€” it points to a different branch file. Study the diagram: pointers all the way down.
Student: And merging?
Socrates: When you merge, Git takes the commits from one branch and weaves them into another. But here is the crucial thing β€” you must first stand on the branch that will receive the work. Switch to main, then merge feature into it.
Student: So I always go to the destination first, then merge the source into it?
Socrates: Precisely. And after merging, the feature branch has served its purpose. Delete it. A clean workshop is a clear mind. Now β€” create a branch, do some work, come back, and merge. The full cycle.
Example Code:
         HEAD
           β”‚
         main
           β”‚
           β–Ό
    C1 ◄── C2 ◄── C3          After: git switch -c feature
                    \
                     C4  ◄── feature  ◄── HEAD


    git branch                    # list all branches
    git switch -c feature         # create AND switch to new branch
    git switch main               # switch back
    git merge feature             # bring feature's commits into main
    git branch -d feature         # delete merged branch

Your Assignment

Create a new branch called 'feature', switch to it, create a file 'feature.txt', stage and commit it with message 'Add feature', then switch back to main and merge the feature branch.

Git Console
git>