Creating Branches
12.1 Creating a New Branch
To create a branch:
Example:
This only creates the branch, it does not switch to it.
1git branch <branch-name>Example:
1git branch feature/login-authThis only creates the branch, it does not switch to it.
12.2 Creating and Switching in One Step
The most common way:
or the older syntax:
Example:
1git switch -c <branch-name>or the older syntax:
1git checkout -b <branch-name>Example:
1git switch -c feature/cart-ui12.3 Creating a Branch from a Specific Commit
Sometimes you want your branch to start from a particular commit instead of the current one.
Example:
Useful for:
• Fixing older versions
• Starting a patch on historical code
• Creating branches from tags or stable release points
1git branch <branch-name> <commit-hash>Example:
1git branch legacy-fix 3a9f122Useful for:
• Fixing older versions
• Starting a patch on historical code
• Creating branches from tags or stable release points
12.4 Listing All Branches
To see all local branches:
To see remote + local branches:
Remote branches appear as:
1git branchTo see remote + local branches:
1git branch -aRemote branches appear as:
1remotes/origin/main
2remotes/origin/feature/login-auth12.5 Pushing a New Branch to Remote
After creating a local branch, push it to GitHub:
Example:
-u sets upstream tracking, so next time you can simply run:
1git push -u origin <branch-name>Example:
1git push -u origin feature/user-profile-u sets upstream tracking, so next time you can simply run:
1git push
2git pull12.6 Key Takeaways
• git branch <name> creates a branch; git switch -c <name> creates and switches to it.
• Follow clean naming conventions like feature/, bugfix/, hotfix/, and release/.
• You can create branches from any commit or tag, not just the latest one.
• Use git branch -a to view local and remote branches.
• Use git push -u origin <branch> to publish a new branch and set upstream tracking.
• Follow clean naming conventions like feature/, bugfix/, hotfix/, and release/.
• You can create branches from any commit or tag, not just the latest one.
• Use git branch -a to view local and remote branches.
• Use git push -u origin <branch> to publish a new branch and set upstream tracking.