Branches and merges

Create and switch branches

Start a feature branch and move your working tree to it.

Before creating a branch, inspect your current state:

git status
git branch --show-current

Create a branch at the current commit and switch to it:

git switch -c add-search

Git creates the add-search reference, then points HEAD to it. The working tree still represents the same commit, so the files might not visibly change yet.

Verify the result:

git branch --show-current
git log -1 --oneline --decorate

Now create a commit. Only add-search moves to the new commit.

Switch back to main

Later, return to the main branch:

git switch main

Switching updates the working tree and index to match the destination commit. Git refuses when that update would overwrite conflicting local changes.

Do not solve that refusal by discarding work. Commit the change if it is coherent, or store it deliberately before switching.

If you need to park unfinished work temporarily, git stash push -m "wip search UI" saves it and gives you a clean tree. Run git stash pop when you return to the branch.

The older command git checkout -b add-search does the same thing as git switch -c. I prefer switch because it only changes branches and is harder to misuse.

List local branches anytime with:

git branch

The current branch has an asterisk beside its name. That matches what git branch --show-current prints in a script-friendly form.

Be careful switching with uncommitted changes. Git stops you when the checkout would overwrite edits. Commit, stash, or discard deliberately instead of forcing past the warning.

Try this on your own project: create a branch, commit a new file, switch back to main, and confirm the file disappears from the working tree but remains in the branch history.

Lesson completed