ProgramGuru

Create branches and switch safely

Create branches and switch safely

A branch gives a line of work a name. You can develop a feature without moving the main branch until the work is ready to integrate.

What you’ll learn

  • Create and switch branches.
  • Explain HEAD and branch pointers.
  • Use git switch instead of overloading checkout.

Branch without copying the project

  1. main

    Stable line points to commit C.

    A → B → C
  2. branch

    Create feature/search at C.

    two names at C
  3. commit

    Advance only feature/search.

    C → D
C → D

A branch is a movable pointer to a commit

Creating a branch is inexpensive because Git primarily creates another reference. When you commit while that branch is checked out, the branch pointer moves to the new commit.

Modern Git provides git switch for branch switching and git restore for restoring file content. Older tutorials often use git checkout for both jobs; this course teaches the more focused commands first.

Create a feature branch and return to main

Run this in a disposable practice repository unless the lesson explicitly says otherwise.

git switch -c feature/search
# edit files
git add .
git commit -m "Add search draft"

git switch main
git log --oneline --decorate --graph --all

The feature commit advances feature/search. Switching back to main changes the working tree to match main, while the feature branch still names its commit.

Practice: Branches and switch

Your task: Create branches feature/a and feature/b from main. Make one different commit on each. Use the graph log to explain where the histories diverge.

Common pitfall to avoid

Git may refuse to switch when doing so would overwrite uncommitted work. Commit, stash or deliberately restore the relevant changes rather than forcing a switch without understanding what will be lost.

Check your understanding

What happens to a checked-out branch when you create a new commit?
Choose one answer. You can try again.

Answer and explanation

Its pointer moves to the new commit.

Correct.

Branches and switch: what to remember

Create branches and switch safely is complete when you can explain the state being changed before you run the command, not merely repeat the syntax.

Read further: official supporting documentation.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Merge branches and understand fast-forward merges →