gitversion-control

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


I am working on a project which I cloned from a remote repository hosted on GitLab. I made some changes to the project, but I didn’t create any branch and want to now start work on some other new features, but without first pushing my existing work to the remote repository.

I might discard the changes in the new feature or might need to push both the new feature as well as the earlier changes to the remote repository, at a later stage.

From what I know about Git, I think I need to create a new local branch, which I can do using git checkout -b NEW_BRANCH_NAME. Is this the correct way to accomplish what I am trying to do? When I use this command, it creates a new branch. How do I switch back and forth between working on this new branch and the earlier one?


Solution

  • You switch back and forth between branches using git checkout <branch name>.

    And yes, git checkout -b NEW_BRANCH_NAME is the correct way to create a new branch and switching to it. At the same time, the command you used is a shorthand to git branch <branch name> and git checkout <branch name>.