To create a branch in GitHub (via Git), follow these steps. The process involves using both Git (on your local machine) and GitHub (online).
1. Create a Branch Locally Using Git
First, you’ll create a branch on your local machine using Git, and then you can push it to GitHub.
Steps to Create a Local Branch:
- Open a Terminal/Command Prompt on your local machine.
- Navigate to your repository:
cd path/to/your/repository
- Check out the main branch (or any branch you want to branch from):
git checkout main
(Replace
main
withmaster
if your repository usesmaster
as the main branch.) - Create a new branch and switch to it:
git checkout -b new-branch-name
new-branch-name
is the name of your new branch.
- Make changes and commit them to your new branch:
git add . git commit -m "Your commit message"
2. Push the New Branch to GitHub
After creating the branch locally, you need to push it to GitHub to share it with others or for future use.
Steps to Push Your Branch to GitHub:
- Push the branch to GitHub:
git push origin new-branch-name
origin
refers to the remote repository (GitHub).new-branch-name
is the name of the branch you’re pushing.
- After pushing, GitHub will show the new branch under the “Branches” tab of your repository.
3. Create a Branch Directly on GitHub (Optional)
Alternatively, you can create a branch directly on GitHub using the web interface. Here’s how:
- Go to your repository on GitHub.
- In the upper-left corner of the repository page, you’ll see the branch selector (it usually says
main
ormaster
). - Click the branch selector, and in the dropdown, type the name of your new branch.
- Select “Create branch:
new-branch-name
from ‘main'” (or whichever branch you’re currently on). - The new branch will be created, and you can start committing changes directly on GitHub.
4. Switch Between Branches
After creating and pushing branches, you can easily switch between them:
- To switch branches locally:
git checkout branch-name
- To view all branches:
git branch
- To list remote branches:
git branch -r
Summary of Key Git Commands for Branching:
- Create a new branch:
git checkout -b <branch-name>
- Push a new branch to GitHub:
git push origin <branch-name>
- Switch branches:
git checkout <branch-name>
- View branches:
git branch
(local),git branch -r
(remote)