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?

Upvotes: 108

Views: 514407

Answers (5)

Vitalii Shevchenko
Vitalii Shevchenko

Reputation: 1

If you are using RubyMine 2024 version, press:

Ctrl+Alt+N

this will open a dialog window for creating a new branch or switching between existing branches. Alternatively, you can open a new terminal by pressing:

Ctrl+Alt+T

Choose your working directory using the following commands:

  • List directories: ls

  • Change directories: cd

To switch branches, use the following command:

git checkout <branch_name>

Tip: Before switching branches, make sure to check status of your commit with:

git status

All necessary changes should be committed before switching to another branch.

Upvotes: 0

Puneet Bansal
Puneet Bansal

Reputation: 71

To create a new local branch run:

git checkout -b NEW_BRANCH_NAME

Upvotes: 7

Mounir bkr
Mounir bkr

Reputation: 1665

1.To create and switch to a new branch in Git:

git checkout -b new-branch-name
  1. verify if you are working on that branch:

git branch

3.If you want to push this new branch to a remote repository, you can use:

git push origin new-branch-name

Upvotes: 17

Keto
Keto

Reputation: 2215

Since git v2.23, the git switch command has been added as an alternative to git checkout. Subjectively, the syntax is more idiomatic.

git switch --create NEW_BRANCH_NAME
# Short form
git switch -c NEW_BRANCH_NAME

Upvotes: 38

DataCrusade1999
DataCrusade1999

Reputation: 2090

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>.

Upvotes: 179

Related Questions