Sunday, January 12, 2025
HomeProgrammingGit - How to Create a Branch in GitHub

Git – How to Create a Branch in GitHub

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:

  1. Open a Terminal/Command Prompt on your local machine.
  2. Navigate to your repository:
    cd path/to/your/repository
    
  3. Check out the main branch (or any branch you want to branch from):
    git checkout main
    

    (Replace main with master if your repository uses master as the main branch.)

  4. Create a new branch and switch to it:
    git checkout -b new-branch-name
    
    • new-branch-name is the name of your new branch.
  5. 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:

  1. 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.
  2. 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:

  1. Go to your repository on GitHub.
  2. In the upper-left corner of the repository page, you’ll see the branch selector (it usually says main or master).
  3. Click the branch selector, and in the dropdown, type the name of your new branch.
  4. Select “Create branch: new-branch-name from ‘main'” (or whichever branch you’re currently on).
  5. 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)
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x