Skip to content
ImagineWorld

Version Control with Git

node_idnode-book_the-software-developer-s-guide-to-linux_chapter-12-version-control-with-git
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num12
chapter_titleVersion Control with Git
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Git is a distributed version control system (DVCS) that, over the last two decades, has become the most widely used version control system in the world. Although it is very likely that you already know the basics of how to use Git, you might not be familiar with common command-line patterns, or some of its more rarely used (but powerful!) features. We’ll cover those here. This chapter will also give you some background knowledge so that commonly used Git terms make more sense and commonly referenced concepts are clear.

Here’s what you’ll learn about:

  • The basics of Git and distributed version control
  • First-time Git setup
  • Basic Git commands
  • Common Git terminology
  • Two powerful and slightly more advanced Git concepts: bisecting and rebasing
  • Git best practices, especially around using commit messages effectively
  • Useful Git shell aliases that will save you lots of typing
  • GUI tools that you can use to interact with Git

Finally, the Poor man’s GitHub section presents a small but legitimately useful project that you can do to practice and integrate the Linux skills you’ve learned up to this point. We hope you’ll try it out: if you do, your comfort and skill on the command line will benefit tremendously.

Git is a DVCS developed by Linus Torvalds, the creator of the Linux kernel. The origin of Git dates back to 2005 when the relationship between the Linux kernel community and a proprietary distributed version control system called BitKeeper broke down.

In response to this, Torvalds sought to create a free, open-source DVCS that would meet the needs of the Linux kernel development process. Within just a few days, he conceptualized and laid the foundation for Git.

Prioritizing performance, security, flexibility, and non-linear development (supporting thousands of parallel branches), Git quickly gained traction within the software development community. Its design, which emphasizes speed, data integrity, and support for distributed workflows, made it a favorite among developers, and it has since become the de facto standard for version control in the software industry.

What is a distributed version control system?

Section titled “What is a distributed version control system?”

Traditional version control systems (like concurrent versions system (CVS) and others) use a central server that maintains a single, coherent repository state at all times. These systems let developers push and fetch code and allowed the use of branches, tags, and other familiar mechanisms. The important point is that these version control systems were designed with a central authority in mind.

Git and other DVCSs, like Mercurial and Fossil, use a different approach. Each developer has their own complete repository. Other developers, instead of going through a central server, pull from each others’ repositories to fetch changes. In the case of the Linux project, there are hundreds of independent repositories in use by developers. Once a developer feels that the state of one of these repositories is ready, they will ask for the changes to be pulled into the main kernel. This is where the term pull request comes from.

While GitHub, GitLab, sourcehut, and others provide centralized hosting for Git, taking care of things like user authorization and providing many other features surrounding the development of software projects, Git works well without any of these and provides many mechanisms to do so. It is even possible to send and receive patches and groups of commits using email, without ever leaving the command line and Git. This allows for easy collaboration, even when a contributor has nothing but an email address to send a patch to.

Here is a quick refresher on the most important Git command-line basics. These are provided as a reference, not as step-by-step instructions – although we’ve written them so that you can follow along if you want to practice.

First things first: if you’re running Git for the first time on a machine, you may want to set a few global config options.

Set the default branch name to main:

git config --global init.defaultBranch main

Now configure your default name and email (attached to all of your commits):

git config --global user.email "[email protected]"
git config --global user.name "Your Name"

Now you can initialize a new Git repository.

Create a directory and enter it:

mkdir my-repo
cd my-repo

Now tell Git you want to initialize this directory as a new Git repository:

git init

Create a file with some simple content, and show the resulting change that Git detects:

echo "Hello World" >> README
git status

Stage the change you made to be committed, and observe how the output of git status has changed:

git add README
git status

Show the staged content:

git diff --staged

Commit the staged changes:

git commit -m 'Add README file'

This is the short form of the commit command, which specifies the message (-m) directly. There is an interactive version of the commit command, which you’d get by running just git commit.

The interactive version of this command (without the –m option) will open the text editor specified in your shell’s EDITOR environment variable, and once the file is saved and the editor exits – that is, when the $EDITOR command returns – the commit will be written.

The following command will add a remote repository with the local name origin that Git can push to and pull from. This might look similar to the SSH login command that we covered in Chapter 13, Secure Remote Access with SSH, because that’s exactly what Git will use in this case. Git also supports other protocols, such as HTTPS.

git remote add origin [email protected]:repo-path

This is just an example, but when you’re working on a real repository – for example, one that exists on GitHub – you’ll change the hostname and repo-path to match the repository you want to add. GitHub and other source-hosting tools all have clear documentation on how to do this for repositories hosted there.

Push changes from your current branch to the remote Git repository:

git push -u origin HEAD

Pull changes from the remote branch:

git pull

Let’s clone a remote repository – all of the code for a project-based Linux course I created:

git clone https://github.com/groovemonkey/hands_on_linux-self_hosted_wordpress_for_linux_beginners

This will pull down the Git history for the codebase and set the origin of the remote repository to the URL specified. Then you can work on the codebase using all of the Git commands you’ve already learned in this chapter.

As before, you can check the status of the repository:

git status

While this command is typically used to check what was modified, it will also provide you with information on ongoing merges, show affected files during a merge conflict, and help you when bisecting code and in various other situations. It’s worthwhile to check git status when you are not sure what is going on; chances are that you are in a special Git state that you either want to get out of or finish before continuing.

Now that we’ve covered the commands you’ll use most often, let’s get you comfortable with some of the terminology that often confuses people who are new to working with Git.

It can be very helpful to get a basic understanding of Git’s vocabulary. Although it can be confusing when other software mixes these terms up, knowing what they mean in the Git world allows you to work a lot more confidently, for example, when troubleshooting and reading error messages.

Here is an overview of the most common terms and what they mean.

This is essentially a “project,” the root directory of the code that is being managed and tracked by version control – the one containing the .git directory. A repository holds your source code and its history and changes.

This has a similar meaning, only that the code is not checked out. It matches what the .git directory contains. On servers hosting the repositories, such as GitHub, GitLab, sourcehut, or your company’s Gogs or Gitea instances, these are usually in a directory named project-name.git containing only what you’d see in a checked-out (cloned) repository found in project-name/.git.

If you imagine the first commit as the seed of a new repository, a project is made up of various branches. There is a main branch (described below), and often one or more side branches, containing other directions a project is taking.

These might be major version branches, which have bug fixes applied to them but will never be merged back into the main branch. They could be experiments that may or may not ever be merged back into the main branch. Or, they could be new features or bug fix branches that are still in development but will be merged as soon as they’re ready – the possibilities are endless.

This is the default branch, which will be used when initializing or cloning a repository. Depending on the project, it usually contains either the latest (in development) or the latest stable code.

This is the latest commit on a branch. It’s also sometimes referred to as the “tip” of a branch. On the command line, HEAD is also commonly used in combination with relative commits.

For example, HEAD~2 references two commits back; therefore, the following command would show you the log up to two commits ago:

git log HEAD~2

In scripts and daily usage, it can also be used as an alternative to the current branch, because it is the tip of the current branch.

Unlike branches, tags are a way to mark specific commits, for example, to create (and later reference) a specific version of the codebase.

Usually, “shallow” is used to describe checkouts that contain no – or very little – history. Shallow checkouts are used when Git is only used as a means to obtain code, rather than the full repository and its history. This, however, might prevent certain commands and tools that depend on more history from working.

Merging is the process of integrating code from one branch into another branch. This can happen in various scenarios, such as merging a feature branch into the main branch, pulling changes from a remote branch, retrieving code from the Git stash, and so on. These merges can happen in a fully automated way. Sometimes, as in the case of merge conflicts, a merge might need manual intervention.

This is a commit that results from code being merged. When merging code, that merge itself becomes a commit. When there is a merge conflict, this merge commit will have changes resolving that conflict. While technically possible, it’s not a good idea to add any other changes (such as additional bug fixes) to such a commit. Merge commits should contain only the changes that are needed to make that specific merge work.

In the case of conflict-free merges that Git handles automatically, it’s common to just commit them without any manual changes to the code or the message.

When Git is not sure how to merge incoming code, this will result in a merge conflict that you need to manually resolve, usually with a merge tool. Such conflicts can occur when code is being pulled, when code is applied from the stash, when merging branches, or during any other activity that acts on your currently checked-out code. Merge conflicts need to be resolved and then committed. git status will usually tell you how to proceed.

Sometimes it is necessary to put changes away for later retrieval. Git provides a mechanism for this, called the stash. The stash is structured like a stack, making it easy to incrementally apply changes in order by git stash pop -ping from it.

Git is a distributed version control system, which means that every developer has their own full repository and, therefore, can work independently of other developers working on the same project.

Imagine a developer, Steve, who makes some changes to the code in his repository. He wants another developer, Sarah, to integrate these changes into the codebase before an upcoming software release. Steve requests Sarah to pull these changes into her repository – as we saw earlier in the chapter, this is where the term “pull request” comes from.

Since many companies and projects do not use Git as a DVCS, preferring a central, authoritative code repository that all developers pull from and push to, the term “pull request” is now usually used to describe a request to add code to that authoritative repository (or sometimes just into the main branch of a repository).

Note

Because this concept deviates from Git’s decentralized nature, there is no native Git word for it. Different products that implement this workflow (updating the authoritative, central version of the codebase) have different names for it: GitHub calls it a “pull request,” while Launchpad calls it a “merge proposal” and GitLab calls it a “merge request.”

Sometimes it makes sense to only obtain individual changes (commits) from a different branch. A typical example is bug fixes in a development branch, like a feature branch that should be added to a stable branch to be released. This can be done by cherry-picking. Unlike merges where the whole branch is merged, cherry-picking allows you to specify individual commits to add.

git bisect is a way to quickly find a commit causing a change, typically used to identify which commit introduced a certain bug. To do so, one specifies a known “bad” and a known “good” commit. The bad commit contains a bug and the good one is still fine. Git will now present you with commits that you can use to test for the bug. Here is an example:

git bisect start
git bisect bad
git bisect good a0634a0
Bisecting: 675 revisions left to test after this (roughly 10 steps)

The first line starts the bisect. In the second one, we tell Git that the current version is bad, so it contains the bug. Since we know that commit a0634a0 is still good, we specify that on the third line. Of course, this doesn’t have to be a commit but can also be a tag or a branch. Git will then let us know how many versions will still have to be checked.

Now it’s time to test the code for the bug we are trying to find. If it’s present, we type in git bisect bad, otherwise, git bisect good. Rinse and repeat. Eventually, you will end up with the exact commit that introduced the bug.

If you want to get out of this mode and back to the state you were in before, typing git bisect reset will do so.

Depending on what you are trying to find, “good” and “bad” are not the best words and can be confusing when trying to find any other kind of behavior change. So it’s possible to use “old” and “new” instead, to find the commit introducing the new behavior. Keep in mind it’s not possible to mix these terms. It’s either good and bad, or old and new.

There are also ways to speed this process up, such as specifying files or directories, if you know where the behavior was introduced. If you know that a change has to be related to the contents of some/directory or some/other/directory, you can narrow down your search like this:

git bisect start -- some/directory some/other/directory

Git will make sure to consider only commits that make changes to these paths.

There are even more ways to speed this process up, like specifying multiple good commits or even passing a test script that, depending on the exit code, will automatically find the commit. A look into man git-bisect is also helpful if you need to go through a lot of commits.

A git rebase is a common way to keep commit histories easy to follow by “replaying” (really, recreating) a given set of changes (like a feature branch) onto a new base commit, rather than the base commit where they really diverged.

Because development is usually distributed, you may have a “true” commit history like this:

Figure 14.1: “real” commit history

Having multiple feature branch histories intermingled in the history is often more confusing than it is useful, so Git’s rebase feature is used to streamline these feature commits as they are merged.

Feature 1 is merged first, so it uses the original base commit. The history now looks like this:

Figure 14.2: Feature 1 rebased/merged Jan 13th

Feature 3 is the next to be rebased and merged, so now the history looks like this:

Figure 14.3: Feature 3 rebased/merged Jan 14th

Finally, Feature 2 is rebased, resulting in its base commit changing to the Jan. 14th Feature 3 commit. Now we have a nice, streamlined history like this:

Figure 14.4: Feature 2 rebased/merged Jan 15th

GitHub and other centralized Git repository hosts have features that automate this process when merging, so you’ll rarely have to rebase manually on the command line. However, here’s the process for doing so:

  1. Create a new branch and add a commit:
    git checkout -b dave/myfeature
    git commit -m "made some changes"
  2. Presuming the base branch is named main, and some commits have been added since you started developing your branch, you can now “rebase on main”:
    git rebase main

This will modify the Git history to rebase your branch’s commits on the latest main commit, as you saw in the graphic above. Because you’re changing existing history, this may require force-pushing to the authoritative repository (such as the GitHub repository), which can cause other users to have conflicts. Please be aware of this when rebasing.

Now that we have identified some of the key terminology and concepts that you will come across when using Git, we can overview some good practices for writing effective commit messages.

As a general rule, “one change per commit, and one commit per change” is the way to keep your Git commits – and history – useful.

There are many situations where you might only work on one major change, but also add a few minor (unrelated) corrections and improvements to the code. These unrelated changes should generally be committed separately, though. It’s a good idea to keep individual commits focused on the one specific thing you are trying to accomplish: a minor fix, fixing a typo, changing style, adding a (single) feature, and so on. Even if you end up making multiple interrelated changes at once, it might still make sense to split them up into multiple commits later. Committing more frequently can make this process a lot easier.

There are many reasons for this rule. One of the most practical reasons is that when your commits are small, individual changes can be easily cherry-picked or reverted should it become necessary (even if you never expected it while changing the code). Having small, tightly focused commits is also helpful when someone uses git blame to understand a change.

Sometimes, vague suggestions, for example, “keep the commit message short when using git commit,” can be confusing and hard to follow. For context, it makes sense to explain how Git is intended to be used. Git, being a DVCS, allows for patches to be sent as emails. As a result, commit messages themselves – in a way – take the form of emails. The first line is considered the subject line, giving a brief overview of what is done, followed by an empty line and a more verbose summary of what was changed.

Because this is a very open-ended schema, there are some commonly agreed-upon rules. Like all such rules, they may be overridden on a per-project or per-organization basis, but here is an overview of what many well-established open-source projects do:

  • Keep the first line short. It should be a summary using 72 characters or less.
  • Make the first line an imperative verb (such as Add …, Fix …).
  • Capitalize the subject line.
  • If you need more than that, add an empty line and a full summary.
  • Use the body to explain why you have made this change. This can be very helpful for any future reader using git blame.
  • Make sure to describe how you came to your conclusion/implementation, and why it is relevant. This is especially important for complex commits and for commits that might not immediately make sense to someone who is looking only at the code. This can be a tremendous help when tracking down bugs, removing obsolete code later, rewriting systems, or just getting into understanding the code.
  • Consider whether some of what you’re writing in your commit message might not be better added to code comments.
  • Imagine a reviewer or future reader having no context at all. Make sure that the code changes can be easily understood.

With this advice in mind, you should be able to make clear and organized commit messages. Next, we will look at some further advice for easily and effectively using Git.

While this book is strongly focused on building up your command-line skills, it’s worth mentioning that there are some graphical tools available that can make interacting with Git easier for some use cases.

tig and gitk are two examples of graphical repository browsers, which give you a Git interface that’s similar to what many IDEs provide. To try them out, simply navigate to a repository using cd and run gitk or tig. You’ll likely have to install these tools via your package manager; many Unix flavors (including popular Linux distributions and macOS) don’t have them installed by default.

Here are a few useful shell aliases for common Git commands. Feel free to add these to your ~/.bash_aliases file (presuming you’re using Bash):

alias gpo='git push origin $(git branch | grep "*" | cut -d " " -f2)'
alias gp='git pull'
alias gs='git status'
alias gd='git diff'
alias gds='git diff --staged'

If you’re typing in git status dozens of times each day, it can be a huge improvement to add an alias that enables you to type gs instead. Feel free to change these to something even more convenient – that’s what customization is for!

Now let’s zoom out a bit and see how we can practically apply all of this knowledge while building a small Linux server project: your very own private Git server.

In this section, we’ll show you how to set up a remote Git repository for yourself. You only need an SSH account on the remote machine and a Git binary on your local machine (as in, the Git command itself). If Git is already installed on the remote machine, you won’t even need root access.

This is a fun project that will make you comfortable with the basic OS-facing concepts involved with Git. This setup is not necessarily suggested for production use; rather, it will show you that there’s absolutely no magic when it comes to Git. Like everything else in Linux, it’s just files (in this case, remote files and an SSH tunnel).

Depending on whether you have root access and whether you want to share the repository with others, you might want to consider creating a specific user for your shared Git service. This is completely optional.

We will use an SSH account for authentication, so if you share the Git repository, the person you share it with will have the same permissions as that user on the remote machine. It might make sense to create a separate user on the remote machine for this project (named git) if you don’t fully trust your fellow programmers to have access to this account.

This project assumes you’re comfortable setting up SSH and connecting to a server – if you’re a bit rusty on the details, check out the previous chapter: Chapter 13, Secure Remote Access with SSH.

Connect to the server, using the account you want your repository to belong to (such as git, or your own user):

First, check if Git is already installed by running:

git version

This should output the version of Git that is installed on your server. If you receive a message like command not found, then Git is not installed on your system.

To install Git, simply use your system’s package manager to install the git package. On Ubuntu, you’d run:

apt-get install git

Now you can initialize a new bare repository. In this case, we will call it my-project. You can create this wherever you want. For the sake of simplicity, we will assume that it is your home directory:

git init --bare my-project.git

This will create a directory called my-project.git. It is not a file, but a directory structure that Git considers a repository. We won’t go into detail here and it will probably be quite a while before you need to change something.

Believe it or not, that’s actually all you need to do!

You can now disconnect from the server (Ctrl + D if you’re connected via SSH).

Despite it being completely empty, you can already clone the repository. After disconnecting from your server, run the following command from your local machine:

git clone [email protected]:my-project.git

As mentioned earlier, this assumes that you created the repository in the home directory of the myuser user. Starting after the example.com hostname (this might also just be your server’s IP address if you haven’t set up DNS), the path is relative to the user’s home directory. If you want to specify a full (absolute) path, just start with a slash. In other words, using the command git clone [email protected]:/home/myuser/my-project.git would lead to the same directory being cloned.

Git will warn you that you cloned an empty repository. But since this is what we expect, there’s no need to worry.

We can now switch to the cloned directory and start working on the project:

cd my-project
echo "My personal project" >> README
git add README
git commit -m 'initial commit'

Now that we have our first commit, we can push it. The very first push has a minor caveat to be aware of: because the repository is still completely empty, it doesn’t know any branches yet, not even the master branch. Git will tell you this if you only run git push. So just make sure to tell Git the branch when pushing to a new repository for the very first time:

git push origin master

That’s it!

Now you or someone else with access to your SSH account can clone, push to, and pull from this repository. You can even set up hooks and do other fun things. Git is a very powerful tool with a huge variety of features. It can take a while to get used to them, so just consider this your starting point.

The possibilities are endless, and I’m always excited to hear about people using Git for interesting or unique use cases. Have fun!

In this chapter, you learned the basic concepts, commands, and workflows that you need to use Git effectively. Some of the often-used advanced features and terminology should be clearer to you now, and we passed on some advice for “soft” Git skills like writing good commit messages.

The shell aliases we showed you save us hundreds of keystrokes in a day of programming; we hope they are as useful to you as they have been to us, and that you’ll use command aliases for all the hard-to-remember or hard-to-type commands you run daily.

We also hope that you followed along with the Poor man’s GitHub project! Running the commands only takes a few minutes, but if you take an afternoon and really try it out (rent a Linux VM for a few hours, set up a remote repository there, and push some example commits), you’ll get a feel for how powerful and effective your newfound Linux skills can be when they’re combined to solve real-world problems.