Now that you're on a feature branch, it's time to make a commit
there and see the whole point of branching: your commit
advances feature, and main stays exactly where it was.
The commit itself is unremarkable
Committing on a branch uses the same commands you already know:
git add feature.txt
git commit -m "Add feature"
There is no special "commit to branch" command. Git always commits to the branch you're currently on. Every commit extends the current branch by one.
What actually happened
Before the commit, main and feature both pointed at the same
commit. After the commit:
featuremoved forward to point at the new commit.maindid not move.
That's the whole trick. You now have two branches at different points in history, sharing everything up to where they split. Run:
git log --oneline --all --graph
The --all flag tells Git to show commits from every branch, not
just the current one. --graph draws an ASCII picture of how the
branches relate. You'll see two lines of history sharing a common
past, then diverging.
Prove main is untouched
Switch back to main and look:
git switch main
ls
Your new feature.txt is gone. It's not deleted, it just doesn't
exist in main's snapshot. Git rewrote the working directory to
match main, and main never had that file.
Switch back to feature and it reappears:
git switch feature
ls
There it is again. Same disk, different snapshot loaded.
This is why branches are so useful: two versions of the project
can live side by side, and you toggle between them with a single
command. You can experiment on feature for a week, and main
stays untouched and shippable the whole time.
Committing on the wrong branch
The most common branch mistake is making a commit while on the
wrong branch. Say you meant to commit on feature but were still
on main. Two easy fixes:
- If the commit is fresh and you haven't pushed anywhere, you can cherry-pick it onto the right branch and reset the wrong one.
- If you catch it before committing, just
git switch featureand then commit. Your staged changes come along with the switch (as long as they don't conflict with the target branch).
The permanent habit that saves you every time: run git status
before you commit. The first line always tells you which branch
you're on.