Why Branches?
Branches let you develop features in isolation without affecting stable code. The main branch stays clean while you experiment on feature branches.
Branch Commands
# Create a branch
git branch feature-auth
# Switch to it
git switch feature-auth
# or (legacy): git checkout feature-auth
# Create and switch in one command
git switch -c feature-auth
# List branches (* = current)
git branch
# Delete a branch (after merging)
git branch -d feature-authMerging
When your feature is ready, merge it into main:
# Switch to main
git switch main
# Merge feature branch
git merge feature-auth
# Delete the merged branch
git branch -d feature-authResolving Conflicts
Conflicts occur when two branches modify the same lines:
git merge feature-branch
# Auto-merging file.txt
# CONFLICT (content): Merge conflict in file.txtThe file will contain conflict markers:
<<<<<<< HEAD
Content from current branch
=======
Content from incoming branch
>>>>>>> feature-branch
Resolution:
- Open the file and choose which content to keep
- Remove the conflict markers (
<<<<<<<,=======,>>>>>>>) - Stage and commit:
git add file.txt
git commit -m "Resolve merge conflict in file.txt"Comparing Changes
# Differences in working directory
git diff
# Between branches
git diff main feature-auth
# Between commits
git diff abc123 def456Viewing File History
# Who changed each line
git blame filename.txt
# History of a specific file
git log --follow filename.txtUndoing Changes
Revert (Safe — creates new commit)
git revert HEAD # Undo last commit
git revert abc123 # Undo specific commitReset (Destructive — removes commits)
git reset --soft HEAD~1 # Undo commit, keep changes staged
git reset --hard HEAD~1 # Undo commit AND discard changes⚠️
git reset --hard permanently deletes changes. Never use it on commits already pushed to a shared repository.
Tags
Tags mark specific commits (usually releases):
git tag v1.0.0
git tag -a v1.0.0 -m "First stable release"
git tag # List tags
git push origin v1.0.0 # Push tag to remoteSummary
- Branches isolate work;
git switch -c namecreates and switches git mergecombines branches; conflicts require manual resolutiongit revertsafely undoes commits;git resetrewrites historygit diffshows changes;git blameshows line-by-line authorship- Tags mark releases:
git tag v1.0.0
Next Steps
Next, we'll connect to GitHub — clone repos, push/pull, and collaborate with pull requests.