Creating and Switching Branches
git branch, git checkout, git switch, create branch, delete branch, branch naming conventions
Creating and Switching Branches
Creating and switching branches are the most frequent Git operations in professional development. Git provides two commands for switching branches: the older git checkout and the newer git switch. Both work, but git switch is more explicit and safer.
Creating a Branch
To create a new branch without switching to it:
git branch feature/user-loginTo create and immediately switch to it:
git switch -c feature/user-login
# or the older syntax:
git checkout -b feature/user-loginSwitching Between Branches
To switch to an existing branch:
git switch main
# or:
git checkout mainBefore switching, ensure your working directory is clean. Either commit your changes or stash them with git stash.
Branch Naming Conventions
Consistent naming makes large repositories manageable. Common patterns include: feature/feature-name for new features, fix/bug-description for bug fixes, docs/section-name for documentation, and chore/task-name for maintenance tasks.
Deleting a Branch
After a feature branch is merged, delete it to keep the repository clean:
git branch -d feature/user-loginThe -d flag only deletes a branch that has been fully merged. Use -D to force-delete an unmerged branch.
