Feature Branch Workflow in Git: How to Use It Effectively
The
feature branch workflow means creating a new branch for each new feature or fix, separate from the main code. You work on the feature branch, then merge it back into main after review and testing to keep the main code stable.Syntax
The feature branch workflow uses these main Git commands:
git checkout -b feature-name: Create and switch to a new feature branch.git add .andgit commit -m "message": Save your changes on the feature branch.git checkout main: Switch back to the main branch.git merge feature-name: Merge the feature branch into main after review.git branch -d feature-name: Delete the feature branch after merging.
bash
git checkout -b feature-name
# Work on feature
git add .
git commit -m "Add new feature"
git checkout main
git merge feature-name
git branch -d feature-nameExample
This example shows creating a feature branch, making a change, and merging it back to main.
bash
git checkout -b feature-login
# Edit files to add login feature
git add .
git commit -m "Add login feature"
git checkout main
git merge feature-login
git branch -d feature-loginOutput
Switched to a new branch 'feature-login'
[feature-login abc1234] Add login feature
Switched to branch 'main'
Updating abc1234..def5678
Fast-forward
Deleted branch feature-login (was abc1234).
Common Pitfalls
Common mistakes include:
- Working directly on
maininstead of a feature branch, risking unstable code. - Not regularly updating the feature branch with changes from
main, causing merge conflicts later. - Forgetting to delete feature branches after merging, cluttering the branch list.
bash
## Wrong: committing directly on main # git add . # git commit -m "Work on feature directly" ## Right: use feature branch git checkout -b feature-xyz git add . git commit -m "Work on feature safely"
Quick Reference
| Command | Purpose |
|---|---|
| git checkout -b feature-name | Create and switch to a new feature branch |
| git add . | Stage changes for commit |
| git commit -m "message" | Save changes with a message |
| git checkout main | Switch back to main branch |
| git merge feature-name | Merge feature branch into main |
| git branch -d feature-name | Delete feature branch after merge |
Key Takeaways
Always create a new branch for each feature to keep main stable.
Commit your changes on the feature branch before merging.
Merge feature branches back into main only after review and testing.
Keep your feature branch updated with main to avoid conflicts.
Delete feature branches after merging to keep your repo clean.