Creating Branches in Git
We’ve been making great progress on our project so far. However, change things up a bit and make some code changes in the project.
Our changes might break the project, so we need to do it in a way that is isolated. We will use a new branch in Git to make the changes and then merge that branch back in when we’re done.
To create a new branch, we want to first make sure we can a clean working directory.
$ git status On branch master nothing to commit, working directory clean
Now let’s create a new branch called
ri_refactoring-code. I’m namepsacing the branch with my initials and then giving a descriptive name of what I’m doing in the branch. You can name branches whatever you want, and the namespacing isn’t required. I simply find it helpful .
To create branches we use the
git-branch command, followed by the branch name.
$ git branch ri_refactoring-code
To see a listing of branches we run
git-branch without any arguments.
$ git branch * master ri_refactoring-code
We see our newly created branch.
Right now the new branch is exactly like the
master branch. The new branch is based off
master because that was the branch we had checked out at the time of running
The asterisk next to the
master branch in the output above denotes that is the current branch.
To switch over to our new branch we use
git-checkout, passing in the name of the branch we want to check out.
$ git checkout ri_refactoring-code Switched to branch 'ri_refactoring-code'
Alright, now we’re ready to change the code! Don’t forget: anything we change in the current branch will not impact the
Let’s make a change in the
1-basics.rb file and add a new
puts statement at the top, below the original one. This is only a small change but we want to get to the next task: merging the changes in our
ri_refactoring-code branch into our
Before we can do that we have to first have to add and commit the changes.
$ git commit -a -m "adding puts statement at the top of the basics file"
With that done, we can do our merge, which we cover in the next chapter.