Getting Started with Git Branches

In this walkthrough, we will be witnessing the power of being able to manage different versions of a file utilizing branches in Git. We start by creating a directory with a python file called

# Create the directory.
$ mkdir hello-world
# Go inside the directory.
$ cd hello-world
# Create the python file.
$ touch

We’re ready for our first commit! But first, we must create a new Git repository then do something called stage the file. After your first commit, create a new branch called feature — we’ll get back to it later.

# Initialize the Git repository.
$ git init
# Stage the file.
$ git add
# Commit the newly created file and add a message.
$ git commit -m "Create hello world python file."
# Create the feature branch.
$ git branch feature

So even through we created a branch called feature, we are currently on master Don’t believe me? Run git branch to see for yourself.

$ git branch
* master

From within the python file simply print Hello world from the master branch! then save and close the file.

print("Hello world from the master branch!")

Let’s run the python file to make sure that it works.

$ python
Hello world from the master branch!

As previous, go ahead and stage the file then commit.

# Stage the file
$ git add
# Commit the changes with our newly added file contents.
$ git commit -m "Say hello from master."

The following diagram illustrates how our two commits currently look like in Git:

Remember that feature branch we created? We’ll be using that now. Go ahead and switch to it using git checkout feature

$ git checkout feature
Switched to branch `feature`

When we run our file python we’ll notice that nothing is printed. This is because the feature branch is at the same place when we last created it — at our first commit. Using your newfound knowledge of Git, do the following:

  1. Inside add code to print Hello world from the feature branch!
  2. Commit the changes to with the commit message Say hello from master. Don’t forget to stage the file before commiting!

To Git, our commits now look like:

Now this is where things get interesting. Run the python file to see that it prints exactly what we would expect to be Hello world from the feature branch!

$ python
Hello world from the feature branch!

Switch to the master branch with the checkout command.

$ git checkout master
Switched to branch `master`

Run the python script and marvel in amazement as the output matches the version of the file way back when we committed to our master branch!

$ python
Hello world from the master branch!

Software Engineer