乐闻世界logo
搜索文章和话题

How to Create and Switch to a New Branch in Git?

2024年7月4日 00:15

When using Git to manage project source code, creating new branches helps isolate the development and testing of different features to ensure the stability of the main branch. Creating and switching to a new branch can be completed through the following steps:

  1. Open the terminal: First, open your command-line tool.
  2. Navigate to your project directory: Use the cd command to switch to your project directory. For example:
    shell

cd path/to/your/project

shell
3. **Check existing branches**: Before creating a new branch, verify all current branches to ensure the new branch name does not conflict. Use the command:

git branch

shell
4. **Create and switch to a new branch**: The simplest approach is to use the `git checkout` command with the `-b` option. For example, to create a branch named `feature-x`, use:

git checkout -b feature-x

shell
This command is a shorthand for two operations: `git branch feature-x` (to create the branch) and `git checkout feature-x` (to switch to it). 5. **Verify the current branch**: After creating and switching, confirm your current branch with:

git branch

shell
At this point, the newly created branch `feature-x` will display an asterisk (*) marker, indicating active work on this branch. Through these steps, you have successfully created and switched to a new Git branch. This is highly useful for feature development, bug fixes, and various experiments, as it allows you to freely modify and test code without impacting the main branch.
标签:Git