0
0
Gitdevops~5 mins

Creating branches with git branch - Step-by-Step CLI Walkthrough

Choose your learning style9 modes available
Introduction
When working on a project, you often want to try new ideas without changing the main work. Creating branches lets you do this by making a separate copy of your project to work on safely.
When you want to add a new feature without affecting the main code.
When you need to fix a bug but keep the fix separate until it's tested.
When you want to experiment with changes without risking the main project.
When collaborating with others and each person works on their own branch.
When preparing a version of the project for release while continuing development.
Commands
This command creates a new branch named 'feature-login' to work on a login feature separately.
Terminal
git branch feature-login
Expected OutputExpected
No output (command runs silently)
This command lists all branches in the repository, showing the current branch with a star.
Terminal
git branch
Expected OutputExpected
main * feature-login
This switches your working area to the 'feature-login' branch so you can start working there.
Terminal
git checkout feature-login
Expected OutputExpected
Switched to branch 'feature-login'
This deletes the 'feature-login' branch after you finish or decide not to use it anymore.
Terminal
git branch -d feature-login
Expected OutputExpected
Deleted branch feature-login (was abc1234).
-d - Deletes a branch safely if it has been merged.
Key Concept

If you remember nothing else from this pattern, remember: branches let you work on changes separately without affecting the main project.

Common Mistakes
Creating a branch but not switching to it before making changes.
Your changes will still go to the current branch, not the new one.
After creating a branch, use 'git checkout branch-name' to switch to it before editing.
Deleting a branch that has unmerged changes with 'git branch -d'.
Git will refuse to delete it to prevent losing work.
Use 'git branch -D branch-name' to force delete, but only if you are sure you want to lose those changes.
Summary
Use 'git branch branch-name' to create a new branch.
Use 'git branch' to list all branches and see which one is active.
Use 'git checkout branch-name' to switch to the new branch and start working.
Use 'git branch -d branch-name' to delete a branch safely after merging.