How To Combine Branches With Git Merge

Ekekenta Odionyenfe .C

Read more posts by this author.

Merging programs into a single file has been a pain, and you’re not the only one in this scenario. But don’t worry, the git merge command can help.

In this article, you’ll learn how to integrate branches with the git merge command together with one of the most extensively used project management tools, GitHub.

Ready? It’s time to dive in!

Prerequisites

This tutorial will be a hands-on demonstration. If you’d like to follow along, be sure you have the following:

  • Git – This tutorial uses Git 2.25.1
  • GitHub Account
  • An Ubuntu machine – This tutorial uses Ubuntu 20.04, but any OS with Git installed will work.

Initializing a Git Project

Before merging branches, you’ll need to initialize a Git project. But first, you’ll create a demo project to push to a GitHub repository later.

1. Open your terminal and run the commands below to create a directory named ~/git-demo (~ implies the home directory), and navigate to that directory.

mkdir git-demo && cd git-demo

2. Next, open your preferred code editor, create a file named ~/git-demo/index.html, then paste the code below to that file.

When you open the index.html file on a web browser, the code prints a “Let’s get started with git merge” message.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h4>Let's get started with git merge</h4>
</body>
</html>

3. Run the command below to initialize a Git project. The command initiates the creation of a new Git repository and creates a .git folder in your project root directory.

The git init command may convert a previously unversioned project to a Git repository or create a new/empty repository.

git init
Initiating an empty Git repository.
Initiating an empty Git repository

4. Run the command below to verify if the .git folder exists in your project root directory.

The command below lists all files, including hidden files, in the working directory.

ls -la
Listing directory files including hidden files to verify the GIT repository exists.
Listing directory files including hidden files to verify the GIT repository exists.

5. Now run the git add command below to stage your code. The command below promotes pending changes from the working directory to the staging area. If the command is successful, no console output is returned.

git add index.html

6. Run the git status command below to verify you’ve staged the code. In the screenshot below, you see the changes to be committed, which indicates you’ve staged the index.html file. git status

git status
Verifying if the code is staged to be committed.
Verifying if the code is staged to be committed

7. Now run the command below to save any changes git commit in the code (index.html) to the master branch, with a message of "initial commit" passed via the -m message parameter for documentation.

git commit -m "initial commit"
Committing changes to the code (index.html)
Committing changes to the code (index.html)

If this is your first time using Git on your system, you will need to set your name and email with the commands:

git config --global user.email "[email protected]"

git config --global user.name "Your Name"

Perhaps you want to see your commit history. If so, run the git log command to list all commits you’ve made so far in your repository.

git log
Listing the Git log.
Listing the Git log.

8. Finally, run the git command below to list all branches available in your repository and verify if the master branch exists.

The default branch is typically named main in recent Git releases instead of master.

git branch
Listing all branches
Listing all branches

Creating a New Git Branch

Now that you have initialized and made your first commit to Git, you’ll create another branch to save changes you’ll make in the index.html file*.*

1. Edit index.html and replace the contents with the code below. Unlike the previous version of the index.html file, the code below displays input fields for username and password.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h4>Let's get started with git merge</h4>
    <form action="">
      <input type="text" name="username" />
      <input type="password" name="password" />
    </form>
</body>
</html>

2. Next, rerun the git status command to see changes in your repository.

Since you’ve made changes to the index.html file, the output below shows the index.html has been modified and is unstaged.

Inspecting Changes in Repository
Inspecting Changes in Repository

3. Run the git checkout command below to create a new branch named “form” (-b form) and automatically switches the current branch from master to form. You can name your new branch to suit your needs.

git checkout -b form
New Branch
New Branch

4. Now rerun the git branch command, and this time you’ll see two branches available on your repository (form and master).

git branch

Below, you see that the form branch begins with the asterisk (*) symbol, which indicates the current working branch is the form branch.

form branch begins with the asterisk (*)
form branch begins with the asterisk (*)

5. inally, run the commands below to stage and commit the changes you made on the index.html file to the form branch.

Once the commands are complete, you’ll have two branches with two different versions of the same file (index.html). The master branch contains the initial code in the index.html file, while the form branch contains the recent changes you made on the index.html file.

## Stage the file
git add index.html

## Commit the changes
git commit -m "Added a form file"
Committing changes to the "form" branch
Committing changes to the “form” branch

Merging Git Branches Locally

Now that you have different branches to your GitHub repository, it’s time to combine those branches. There are various ways of combining branches, here you learn how to merge branches locally.

1. Run the git checkout command below to switch to the master branch since you’ll update it with the code from the form branch.

git checkout master

2. Run the commands below to combine your target branch (form) with the current branch (master).

git merge form
Merging branches with git merge command.
Merging branches with git merge command.

3. Verify that the changes have been merged by verifying you are on the master branch and that the content has changed.

# Verify Branch
git branch
# View output
cat index.html
Verifying the index.html content after a Git merge.
Verifying the index.html content after a Git merge.

Squashing Git Branches

You may be adding new features to a branch with commit messages that you don’t need to keep. Combine these commit messages into one commit message with squashing. Squashing enables you to tidy up the commit history of a branch when accepting a merge request.

To demonstrate the effect of squashing, you’ll be making changes in the index.html file, then stage and commit after each change.

1. Run the command below to switch to the form branch.

git checkout form

2. Next, update the index.html file by adding a form header

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h4>Let's get started with git merge</h4>
    <form action="">
      <!-- Added a form header -->
      <h4>Enter account details</h4>
      <input type="text" name="username" />
      <input type="password" name="password" />
      <button>Submit</button>
    </form>
</body>
</html>

3. Run each command below to stage and commit the changes with a message ("Added a header to form").

# Stage the changes
git add index.html
# Commit the changes
git commit -m "Added a header to form"
Adding content to the index.html file.
Adding content to the index.html file

4. Now, add an extra input field shown below under the form header (<h4>Enter account details</h4>) in the index.html file.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h4>Let's get started with git merge</h4>
    <form action="">
      <!-- Added a form header -->
      <h4>Enter account details</h4>
      <input type="text" name="fullname" />
      <input type="text" name="username" />
      <input type="password" name="password" />
      <button>Submit</button>
    </form>
</body>
</html>

5. Stage and commit the changes as you did in step three, but change the commit message.

# Stage the changes
git add index.html
# Commit the changes
git commit -m "Added an extra input field to form"
Adding additional content to index.html.
Adding additional content to index.html

6. Add a paragraph (<p>Already a user?</p>) under the form block, as shown below in the index.html file.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h4>Let's get started with git merge</h4>
    <form action="">
      <!-- Added a form header -->
      <h4>Enter account details</h4>
      <input type="text" name="fullname" />
      <input type="text" name="username" />
      <input type="password" name="password" />
      <button>Submit</button>
    </form>
    <!-- Add a paragraph -->
    <p>Already a user?</p>
</body>
</html>

7. Stage and commit the changes with a different commit message ("Added a paragraph to file").

# Stage the changes
git add index.html
# Commit the changes
git commit -m "Added a paragraph to file"
Adding a final commit to demonstrate a variety of commit messages.
Adding a final commit to demonstrate a variety of commit messages

8. Run the git rebase command below to open Git in an interactive mode (-i) on your default command-line text editor, and see your three recent commits (HEAD~3).

git rebase -i HEAD~3

9. Now, for the first commit, remove pick and add reword. For the second and third commits remove pick and add squash at the beginning of the commit lines. Doing so combines the second and third commits to the first commit, while prompting for a new commit message upon save.

Squashing Git Commits
Squashing Git Commits

10. After saving, modify the commit message that describes the union of the commits you made (step nine). Save the changes, and exit the editor.

Modifying the Git Commit Message
Modifying the Git Commit Message

If squashing is successful, you’ll see an output similar to the one below.

Confirming Git Squash is a Success
Confirming Git Squash is a Success

Perhaps, you prefer to squash your commits while merging the branches simultaneously. If so, append the --squash switch to the git merge command like the one below. The command below merges the form branch with the master branch and squashes the commits in the form branch.

git merge --squash form

You’ll see an output like the one below if the command runs successfully.

Squashing during a merge
Squashing during a merge

Fast-forwarding a Git Branch

Perhaps you prefer to keep your commit history clutter-free while merging branches without messing things up. If so, fast-forwarding is the solution and is what developers typically use for minor feature updates or bug fixes.

Fast-forwarding lets you merge branches without creating other merge commits (3-way merge). But mind you that fast-forwarding only occurs when there’s no commit made in one of the branches, preferably the main branch. Fast-forwarding combines histories and moves the current branch pointer to the target branch.

1. Run the below command to switch to the form branch.

git checkout form

2. Next, create a JavaScript file and add any code snippets to that file. You can name the file differently, but the file is named index.js for this example.

3. Stage (git add) and commit (git commit) the changes.

git add index.js
git commit -m "Created a new file"

4. Lastly, run the commands below to switch to the master branch and merge it with the form branch. You’ve only made commits to the form branch, so there’s no divergence made in the master branch, leaving a linear path from the master to the form branch.

The git merge command integrates the commit histories and moves the master branch’s pointer forward to the form branch.

## Switch to the master branch
git checkout master
## Fast-forward (merge) the master branch to the form branch
git merge form
Fast-forwarding the master branch to the form branch
Fast-forwarding the master branch to the form branch

Conclusion

Throughout this tutorial, you’ve learned how to combine branches of your Git project. The git merge and other Git commands let you work with other developers on the same project without messing things up.

Now, to experience more about combining branches, why not collaborate with other developers and contribute to GitHub projects?

Subscribe to Stay in Touch

Never miss out on your favorite ATA posts and our latest announcements!

Looks like you're offline!