Search⌘ K
AI Features

Create a Branch

Explore how to create and manage branches in Git using the git switch command. Understand making commits on new branches and switching between them to efficiently organize your code development.

So far, we’ve learned the basic commands to keep adding changes as snapshots. It’s time to learn some more techniques.

In this chapter, we’ll learn to do the following:

  • We’ll learn to create branches.
  • We’ll learn to check out a specific commit.
  • We’ll learn to merge branches.
  • We’ll learn check the difference between commits.
  • We’ll learn to keep a clean commit history.
  • We’ll work with git add interactively to select only the changes we want to commit.

Create a branch

We can create a branch using git switch -c. For example, the following command creates a branch named new_feature:

$ git switch -c new_feature

This creates a new branch. But actually, nothing really changes here until we create new commits. When we git log the commits, we still see the same commits graph. The only difference is now there’s a new_feature branch name that appears where the HEAD is at.

Make changes in the new branch

We’ll see how the branch works when we make changes and commit it. Afterward, the git log shows a commit-graph that contains the new_feature and the master, which points to two different commits. This is because we created a branch from where the master pointed at it and then moved forward with new commits.

Run the following commands in the terminal below:

  1. Create some files.
    $ touch file2.txt
    
  2. Run the git add . command.
    $ git add .
    
  3. Run the following git commit command:
    $ git commit -m "First commit in new_feature branch."
    
  4. Run the git log command.
    $ git log
    
  5. Go back to the master branch.
    $ git switch master
    
  6. Make changes in master.
    $ touch file3.txt
    $ git add .
    $ git commit -m "Make changes in master."
    
  7. Run the git log command again.
    $ git log --oneline --graph --decorate --all
    
Terminal 1
Terminal
Loading...

Make changes in the master branch

To make things more interesting, let’s go back to the master branch using git switch master. Now, HEAD points to master.

Next, we make some other changes on master and commit them. When we use git log to see the commit-graph, we see two commits branching out from the same parent commit, but now one is master, and the other is new_feature. The HEAD points to the current commit. When we use git switch new_feature again, we can see the HEAD now points to new_feature.

Note: If we use an older version of the Git client, we may not have the git switch command. We can use git checkout branch_name to switch between branches and git checkout -b new_branch_name to create a new branch.