How to create new local branch and switch between branches in Git

53    Asked by LarryHuffer in Devops , Asked on Jan 7, 2025

How do you create a new local branch in Git, and what is the process for switching between branches? What commands or steps do you typically use to manage your branches effectively in a Git repository?

Answered by Manish Nagar

To create a new local branch and switch between branches in Git, you can follow these steps:

Create a New Branch: To create a new branch, use the git branch command followed by the name of the new branch. For example:

git branch new-branch-name This creates a new branch, but it does not switch to it immediately.

Switch to the New Branch: After creating the branch, you can switch to it using the git checkout command:

git checkout new-branch-name Alternatively, in newer versions of Git, you can use the shorthand git switch:

git switch new-branch-name This switches the working directory to the newly created branch.

  • Create and Switch in One Command: You can also combine both actions into a single command. This creates the new branch and switches to it immediately:
  • git checkout -b new-branch-name Or using the git switch command:
  • git switch -c new-branch-name
  • List Branches: To view all the branches in your repository, use the git branch command. The current branch will be marked with an asterisk:
  • git branch
  • Switch Between Existing Branches: To switch between existing branches, simply use the git checkout or git switch command followed by the branch name:
  • git checkout existing-branch-name Or:
  • git switch existing-branch-name
  • Verify the Switch: You can confirm you're on the correct branch by running git status or git branch, which will show the current active branch.

By using these commands, you can efficiently create new branches, switch between them, and manage your development workflow in Git.



Your Answer

Interviews

Parent Categories