Intern
What is a branch in Git?
sobes.tech AI
Answer from AI
A branch in Git is an independent line of development. It is a pointer to a specific commit. When creating a new branch, Git copies the pointer to the current commit. All subsequent changes are fixed in the new branch without affecting others.
Advantages of using branches:
- Work isolation: Allows working on new features or bug fixes without affecting the stable version of the project or other developers' work.
- Parallel development: Multiple developers can work simultaneously on different features in their branches.
- Experiments: You can safely experiment with new ideas without fear of damaging the main codebase.
Example of creating a branch:
// Create a new branch named feature/my-new-feature
git branch feature/my-new-feature
Switching to a branch:
// Switch to the branch feature/my-new-feature
git checkout feature/my-new-feature
Short command for creating and switching:
// Create a branch and switch to it immediately
git checkout -b feature/my-new-feature
Viewing existing branches:
// Show a list of all branches
git branch
// Show a list of remote branches
git branch -r
// Show a list of all branches (local and remote)
git branch -a
Merging branches combines changes from one branch into another.
// Switch to the branch where changes need to be merged (e.g., main)
git checkout main
// Merge changes from the branch feature/my-new-feature into the current branch (main)
git merge feature/my-new-feature
Deleting a branch:
// Delete the branch feature/my-new-feature (if changes are already merged)
git branch -d feature/my-new-feature
// Force delete the branch feature/my-new-feature (even if changes were not merged)
git branch -D feature/my-new-feature