Hone

Lessons · Git · moving between branches

Moving between branches

git switch name moves you onto that branch and changes the working tree to match. git switch -c name creates the branch first.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

switch is the modern, narrower replacement for checkout: it changes branches and nothing else, so it cannot accidentally discard a file the way checkout could.

How to think about it

Commit or stash before switching; if switch refuses, it is protecting an edit that would be overwritten. -c when the branch is new, - to go back where you were.

Worked example

git switch -c topic
Creates topic at the current commit and moves onto it.
git branch --show-current
topic.
git switch main
Back to main; the working tree changes to match.
git switch -
The previous branch, like cd -.

Your turn

Start a new branch for the fix and move onto it.

git switch  fix-typo

The trap

switch refuses to move if uncommitted changes would be overwritten. Commit or stash; the refusal is protecting your work.

Practise moving between branches on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.