13 Creating and Switching Branches

Git’s branches enable you to separate experimentation from production-ready code. Git’s convention is to treat the master branch as its main line of code. You can rename it to anything you want, but it’s a good idea to keep with the convention.

You can create a new branch using the git branch command and providing it at least one additional parameter: the name of the branch you want to create. This uses your current location in the repository as the place to create the branch from.

You can also create branches starting at points in the history of the repository. Provide git branch with the name of the new branch you want to create followed by the commit ID or branch or tag name to create a branch at that point.

Following the “do one thing, do it well” idiom, git branch just creates the branch; you have to switch to it. You can use the git checkout command to check out the new branch.

Creating a new branch and checking it out immediately is common in Git. You can do both actions with one command: git checkout -b. Like git branch, it requires at least one parameter—the name of the new branch—and takes an optional second parameter specifying the point to create it from.

Tracking branches store additional metadata information about the relationship between two branches. The most common tracking branch is a local branch that tracks a remote branch (something Git does for you by default). The additional metadata is used by other commands, such as git push and git status, to provide additional functionality.

What To Do...
  • Create a new branch from current place in the repository.
     
    prompt>​ git branch <new branch name>
     
    ...​ example ...
     
    prompt>​ git branch new
     
    prompt>
  • Create a new branch from another branch, tag, or commit.
     
    prompt>​ git branch <new branch name> <starting point>
     
    ...​ example ...
     
    prompt>​ git branch newer 99a0de8
     
    prompt>
  • Check out a different branch, tag, and so on.
     
    prompt>​ git checkout <branch>
     
    ...​ example ...
     
    prompt>​ git checkout newer
     
    Switched to branch 'newer'
  • Create a branch and check it out at the same time.
     
    prompt>​ git checkout -b <new branch> [<starting point>]
     
    ...​ example ...
     
    prompt>​ git checkout -b newest 64648c9
     
    Switched to branch 'newest'
  • Create a branch with or without tracking.

    Using a remote branch as your <starting point> implies that --track is on. Use --no-track to turn it off.

     
    prompt>​ git branch --track <new branch> [<starting point>]
     
    prompt>​ git branch --no-track <new branch> [<starting point>]
     
    prompt>

Related Tasks

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.70.21