Git Branch Command Overview
Branches are essential in Git for enabling collaboration and independent development.
This post summarizes the key commands related to Git branches. By using branches, you can manage multiple development tasks in parallel without conflicts.
1. Check Branch List (git branch)
git branch
Function: Displays all branches in the local repository.
Option:
git branch -a # Shows both local and remote branches
Example:
git branch -a
2. Create a New Branch (git branch <branch-name>)
git branch feature/login
Function: Creates a new branch.
Note: The branch is not switched to automatically after creation.
Example:
git branch feature/login
3. Switch Branches (git checkout)
git checkout <branch-name>
Function: Switches to a different branch.
Example:
git checkout feature/login
4. Create and Switch Branch Simultaneously (git checkout -b)
git checkout -b feature/signup
Function: Creates a new branch and switches to it immediately.
Example:
git checkout -b feature/signup
5. Delete a Branch (git branch -d)
git branch -d feature/login
Function: Deletes a branch from the local repository.
Note: Use the -D option to force delete an unmerged branch.
Example:
git branch -D feature/old-feature
6. Delete a Remote Branch (git push origin –delete)
git push origin --delete <branch-name>
Function: Deletes a branch from the remote repository.
Example:
git push origin --delete feature/signup
7. Merge Branches (git merge)
git merge <branch-name>
Function: Merges changes from another branch into the current branch.
Example:
git checkout main
git merge feature/login
8. Resolve Conflicts and Complete the Merge
If conflicts arise during the merge, Git will request a resolution. Once resolved, commit the changes:
git add .
git commit -m "Merge conflict resolved"
9. Rebase to Organize Commits (git rebase)
git rebase <branch-name>
Function: Reorders commits from one branch on top of another.
Example:
git checkout feature/login
git rebase main
10. Set Upstream Tracking (git branch –set-upstream-to)
git branch --set-upstream-to=origin/main
Function: Links a local branch with a remote branch for tracking.
Example:
git branch --set-upstream-to=origin/main feature/login
Conclusion
By mastering Git branch commands, you can efficiently manage your project’s codebase and develop multiple features in parallel. It’s particularly important to establish branch usage guidelines and proactively prevent conflicts during merges when working in teams.
Start using these commands to manage your branches systematically and improve your workflow! 🚀
Leave a Reply