Create and switch branches (git branch, git checkout)
In Git, branches are one of the core tools in the development workflow. By creating and switching branches, you can efficiently manage parallel development tasks and isolate code changes for different features or fixes. Understanding the usage of the git branch
and git checkout
commands can significantly enhance team collaboration and version control capabilities.
Basic Concepts of Branches
Git branches are essentially mutable pointers to commit objects. By default, Git creates a primary branch named main
or master
. Each branch represents an independent line of development, allowing experimentation or feature development without affecting the main branch.
To view all branches in the current repository:
git branch
Example output:
* main
feature-login
bugfix-header
The branch marked with *
indicates the currently active branch.
Creating a New Branch
Use the git branch
command to create a new branch. The following command creates a branch named feature-search
:
git branch feature-search
At this point, the branch pointer points to the current commit but does not automatically switch to the new branch. After creating a branch, the local repository adds a new movable pointer pointing to the same commit.
A shortcut to create and switch to a branch:
git checkout -b feature-search
This is equivalent to:
git branch feature-search
git checkout feature-search
Switching Branches
To switch branches, use the git checkout
command. For example, to switch from the main
branch to the existing feature-login
branch:
git checkout feature-login
When switching branches, Git performs three actions:
- Points the HEAD pointer to the target branch
- Replaces the working directory with the snapshot of the target branch
- Updates the staging area to match the target branch
If you attempt to switch to a non-existent branch (without creating it first), Git will report an error:
git checkout non-existent-branch
# Error: pathspec 'non-existent-branch' did not match any file(s) known to git
Branches and Working State
When switching branches, if there are uncommitted changes in the working directory or staging area, you may encounter the following scenarios:
- Changes Do Not Affect Branch Differences: If the modified files have no differences between branches, Git allows the switch directly.
- Changes Affect Branch Differences: Git will prevent the switch and require you to commit or stash the changes first.
For example, if you modified index.html
but did not commit it, attempting to switch branches will result in:
git checkout other-branch
# Error: Your local changes to the following files would be overwritten by checkout:
# index.html
# Please commit your changes or stash them before you switch branches.
Solution:
git stash # Stash the changes
git checkout other-branch
git stash pop # Restore the stashed changes
Branch Naming Conventions
Good branch naming improves project management efficiency. Common naming conventions include:
- Feature branches:
feature/[description]
, e.g.,feature/user-auth
- Bugfix branches:
bugfix/[issue description]
, e.g.,bugfix/login-error
- Release branches:
release/[version number]
, e.g.,release/v1.2.0
- Hotfix branches:
hotfix/[issue description]
, e.g.,hotfix/security-patch
Creating a branch with a prefix:
git checkout -b feature/search-autocomplete
Remote Branch Operations
Local branches can be associated with remote branches. To view remote branches:
git branch -r
Example output:
origin/main
origin/develop
origin/feature/login
Creating a local branch that tracks a remote branch:
git checkout --track origin/feature/login
This is equivalent to:
git checkout -b feature/login origin/feature/login
Underlying Mechanics of Branch Switching
When executing git checkout
, Git performs the following steps:
- Checks if the target branch exists
- Validates the state of the working directory and staging area
- Updates the HEAD file to point to the target branch reference
- Updates the working directory with the tree object pointed to by the target branch
- Updates the staging area index
You can simulate the branch-switching process using low-level commands:
# View current HEAD content
cat .git/HEAD
# Output: ref: refs/heads/main
# Manually modify HEAD
echo "ref: refs/heads/develop" > .git/HEAD
# Update the working directory
git reset --hard
Practical Tips for Branch Switching
- Quickly Switch Back to the Previous Branch:
git checkout -
The hyphen parameter represents the last active branch.
- Detached HEAD State: Checking out a commit directly instead of a branch:
git checkout e3f1e3f
This puts you in a "detached HEAD" state, where new commits will not belong to any branch.
- Create a Branch and Switch to a Specific Commit:
git checkout -b new-branch a1b2c3d
This creates a new branch at commit a1b2c3d
and switches to it immediately.
Branch Management Example
Assume you are developing an e-commerce website. A typical branch operation workflow:
- Create a feature branch from the main branch:
git checkout -b feature/product-filter
- Make multiple commits during development:
// Modified product.js
function applyFilters(products, filters) {
return products.filter(p => {
return filters.every(f => f(p))
})
}
git add product.js
git commit -m "Implement basic filtering functionality"
- Need to urgently fix a bug in the main branch:
git stash
git checkout main
git checkout -b hotfix/checkout-error
# Perform the fix and commit
git checkout main
git merge hotfix/checkout-error
git branch -d hotfix/checkout-error
- Return to the feature branch to continue development:
git checkout feature/product-filter
git stash pop
Notes on Branch Switching
-
Untracked Files: Git does not manage untracked files (files not added with
git add
). These files remain when switching branches. -
Merge Conflict Risk: If switching branches could cause merge conflicts (e.g., both branches modified the same file), Git will abort the switch operation.
-
Performance in Large Repositories: In repositories with many files or large files, switching branches may cause noticeable delays.
-
Submodule Handling: If the project includes Git submodules, switching branches may trigger submodule updates.
Branch Operations in GUI Tools
Most Git GUI tools provide branch management features. For example, in VS Code:
- Click the branch icon in the bottom-left corner.
- Select an existing branch from the list.
- Or click the "+" icon to create a new branch.
- Enter the new branch name and confirm.
GUI tools often visually display branch relationships and commit history.
Best Practices for Branch Strategies
- Short-Lived Branches: Feature branches should have a short lifecycle and be deleted after merging.
- Clear Naming: Branch names should clearly indicate their purpose.
- Regular Sync: Long-lived branches should regularly merge/rebase from the main branch.
- Permission Control: Protect the main branch, allowing merges only via Pull Requests.
Delete merged branches to keep the repository clean:
git branch --merged | grep -v "\*" | xargs -n 1 git branch -d
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:Git分支的本质