Git Basics in Practice
local graph
Chapter 1 — Git Basics in Practice
Section titled “Chapter 1 — Git Basics in Practice”This book is intended for intermediate and advanced Git users to help them on their road to mastering Git. Therefore, the chapters following this one will assume you know the basics of Git, and have advanced past the beginner stage.
This chapter will serve as a reminder of version control basics with Git. The focus will be on providing practical aspects of the technology, showing and explaining basic version control operations on the example of the development of an example project, and the collaboration between two developers.
In this chapter, we will cover the following:
- A brief introduction to version control and Git
- Setting up a Git environment and Git repository (
initandclone) - Adding files, checking status, creating commits, and examining the history
- Interacting with other Git repositories (
pullandpush) - Creating and listing branches, switching to a branch, and merging changes
- Resolving a simple merge conflict
- Creating and publishing a tag
Technical requirements
Section titled “Technical requirements”To follow the examples shown in this chapter, you will need Git: https://git-scm.com/. You will also need an interactive shell (for example, Git Bash if you are using MS Windows), a text editor or an IDE for web development (for editing JavaScript and HTML), and a web browser.
You can access the code of an example project used in this chapter at the following URLs: the book’s companion GitHub repository (chapter01) and https://github.com/jnareb/Mastering-Git---Second-Edition---chapter01-sample_project.
A brief introduction to version control and Git
Section titled “A brief introduction to version control and Git”A version control system (sometimes called revision control) is a tool that lets you track the history and attribution of your project files over time (stored in a repository) and helps the developers in the team to work together. Modern version control systems give each developer their own sandbox, preventing their work in progress from conflicting, and all the while providing a mechanism to merge changes and synchronize work. They also allow us to switch between different lines of development, called branches; this mechanism allows the developer to change, for example, from working on introducing a new feature step by step to fixing the bug in an older, released version of the project.
Distributed version control systems (such as Git) give each developer their own copy of the project’s history, which is called a clone of a repository. This is what makes Git fast, because nearly all operations are performed locally. It is also what makes Git flexible because you can set up repositories in many ways. Repositories meant for development also provide a separate working area (or a worktree) with project files for each developer. Git’s branching model enables cheap local branching, allowing the use of branches for context switching by creating sandboxes for different tasks. It also makes it possible to use a very flexible topic branch workflow for collaboration.
The fact that the whole history is accessible allows for a long-term undo, rewinding to the last working version, and so on. Tracking ownership of changes automatically makes it possible to find out who was responsible for any given area of code, and when each change was done. You can compare different revisions, go back to the revision a user is sending a bug report against, and even automatically find out which revision introduced a regression bug (with git bisect). Tracking changes to the tips of branches with reflog allows for easy undo and recovery.
A unique feature of Git is that it enables explicit access to the staging area for creating commits (new revisions—that is, new versions of a project). This brings additional flexibility to managing your working area and deciding on the shape of a future commit.
All this flexibility and power come at a cost. It is not easy to master using Git, even though it is quite easy to learn its basic use. This book will help you attain this expertise, but let us start with a reminder about the basics of Git.
Git by example
Section titled “Git by example”Let’s follow a step-by-step, section-by-section, simple example of two developers using Git to work together on a simple project. You can find all three repositories (for two developers, and the bare server repository) with the example code files for this chapter, where you can examine the code, history, and reflog, at the book’s companion GitHub repository, in a sample_project.zip archive.
Following the example
To follow this example of the team development process on a single computer, you can simply create three folders called, for example, alice/, bob/, and server/, and switch to the appropriate folder when following work done by Alice, Bob, and Carol, respectively.
There are a few simple changes you need to make for this simulation to work. When creating a repository as Carol, you don’t need to create and switch to the /srv/git directory, so you can simply skip these commands. In Alice or Bob’s role, you need to create separate identities in the repository’s local configuration, either with the git config command without the --user option or by editing the .git/config file in the appropriate repository. In place of the https://git.company.com/random repository URL, which does not exist, simply use the path to the server repository: ../server/random.git.
Additionally, if you plan on moving the directory with alice/, bob/, and server/ subdirectories, you will need to edit the “origin” repository URL that is stored in repository config files by changing it from the absolute path to a relative path—namely, ../../server/random.git.
Setup and initialization
Section titled “Setup and initialization”A company has begun work on a new product. This product calculates a random number—an integer value of a specified range.
The company has assigned two developers to work on this new project, Alice and Bob. Both developers are telecommuting to the company’s corporate headquarters. After a bit of discussion, they have decided to implement their product as a simple web application in JavaScript and HTML and to use Git 2.41.0 (git-scm.com) for version control.
Note
This project and the code are intended for demonstration purposes only and will be much simplified. The details of code are not important here—what is important is how the code changes, and how Git is used to help with the development.
Repository setup
Section titled “Repository setup”With a small team, they have decided on the setup shown in the following diagram.
Important note
This is only one possible setup, with the central canonical repository, and without a dedicated maintainer responsible for this repository (all developers are equal in this setup). It is not the only possibility; other ways of configuring repositories will be shown in Chapter 6, Collaborative Development with Git.

Figure 1.1 – Repository setup for the sample project (using a centralized workflow)
Creating a Git repository
Section titled “Creating a Git repository”Alice gets the project started by asking Carol, an administrator, to create a new repository specifically for collaborating on a project, to share work with the whole team:
carol@server:~$ mkdir -p /srv/gitcarol@server:~$ cd /srv/gitcarol@server:/srv/git$ git init --bare random.gitInitialized empty Git repository in /srv/git/random.git/Important note
Command-line examples follow the Unix convention of having user@host:directory at the beginning of the command prompt, to make it easier to guess from first glance who performs a command, on what computer, and in which directory (here, the tilde, ~, denotes the user’s home directory). This is the usual command prompt setup on Linux; a similar-looking prompt is used by Git Bash.
You can configure your command prompt to show Git-specific information, such as the name of the repository, the subdirectory within the repository, the current branch, and even the worktree status (see Chapter 13, Customizing and Extending Git).
I consider the details of server configuration to be too much for this chapter. Just imagine that it happened, and nothing went wrong, or look at Chapter 14, Git Administration.
You can also use a tool to manage Git repositories (for example, gitolite); creating a public repository on a server would then, of course, look different. Often, though, it involves creating a Git repository with git init (without --bare) in your own home directory and then pushing it with an explicit URI to the server, which would then automatically create the public repository.
Or perhaps the repository was created through the web interface of tools such as GitHub, Bitbucket, or GitLab (either hosted in the cloud, or installed on-premises).
Cloning the repository and creating the first commit
Section titled “Cloning the repository and creating the first commit”Bob gets the information that the project repository is ready, and he can start coding.
Since this is Bob’s first time using Git, he first sets up his ~/.gitconfig file with information that will be used to identify his commits (for example, with git config -- global --edit):
[user] name = Bob Hacker email = [email protected]Now, he needs to get his own repository instance (which currently is empty):
bob@hostB:~$ git clone https://git.company.com/randomCloning into 'random'...warning: You appear to have cloned an empty repository.done.bob@hostB:~$ cd randombob@hostB:~/random$Tip
All examples in this chapter use the command-line interface. Those commands might be given using a Git GUI or IDE integration, as explained in the Graphical interfaces section in Chapter 13, Customizing and Extending Git. The book Git: Version Control for Everyone, shows GUI equivalents for the command line.
Bob notices that Git said that it is an empty repository with no source code yet, and starts coding. He opens his text editor (or IDE of choice) and creates the starting point for their product.
First, he creates an HTML file (index.html) with the simplest possible interface for the web application being created, just a button and an input field:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Random Number Generator</title> <script src="random.js" defer></script></head><body><button disabled>Generate number</button><label for="max">up to</label><input type="number" id="max" name="rand_max" value="10" /></body></html>Then, Bob writes JavaScript source code (random.js) that is responsible for web application behavior—in this case, generating and displaying a random integer number within a given range from 1 to a configurable maximum, inclusive:
function getRandomInt(max) { return Math.floor(Math.random() * max) + 1;}function generateRandom() { let max = document.getElementById('max').value; alert(getRandomInt(max));}let button = document.querySelector('button');button.addEventListener('click', generateRandom);button.disabled = false;Typically, for most initial implementations, this version is missing a lot of features but it is a good place to begin. Before committing his code, Bob wants to make sure that it looks all right and that it works correctly. He opens the index.html file in a web browser or uses a live preview feature of his IDE, as shown in Figure 1*.2*.

Figure 1.2 – Preview of the first version of the example application
Alright! It’s time to add both files to the repository:
bob@hostB:~/random$ git add index.html random.jsBob uses the status operation to make sure that the pending changeset (the future commit) looks proper.
We use a short form of git status here to reduce the amount of space taken by examples; you can find an example of a full status output further in the chapter:
bob@hostB:~/random$ git status --shortA index.htmlA random.jsNow it’s time to commit to the current version:
bob@hostB:~/random$ git commit -a -m "Initial implementation"[master (root-commit) 961e72b] Initial implementation 2 files changed, 25 insertions(+) create mode 100644 index.html create mode 100644 random.jsImportant note
Normally, you would create a commit message not by using the -m <message> command-line option but by letting Git open an editor. We use this form here to make the examples more compact. In actual practice, it is recommended to provide a more detailed description of changes.
The -a / --all option in the git commit -a command means to take all changes to the tracked files. This is not the only possible way of creating revisions; you can separate manipulating the staging area from creating a commit—this is, however, a separate issue, left for Chapter 3, Managing Your Worktrees.
Now it’s time to make those changes visible to Alice.
Collaborative development
Section titled “Collaborative development”One of the main goals of a version control system is to help developers work together on a common project. With a distributed version control system, such as Git, this involves an explicit step of publishing changes to be visible to others.
Publishing changes
Section titled “Publishing changes”After finishing working on the initial version of the project, Bob decides that it is ready to be published (to be made available for other developers). He pushes the changes as follows:
bob@hostB:~/random$ git pushEnumerating objects: 4, done.Counting objects: 100% (4/4), done.Delta compression using up to 4 threadsCompressing objects: 100% (4/4), done.Writing objects: 100% (4/4), 670 bytes | 22.00 KiB/s, done.Total 4 (delta 0), reused 0 (delta 0)To https://git.company.com/random.git * [new branch] master -> masterTip
Note that, depending on the speed of the network, Git could show progress information during remote operations such as clone, push, and fetch. Such information is omitted from examples in this book, except where that information is actually discussed while examining the history and viewing changes.
Also, if you use an older Git version, it could require setting a push.default configuration variable.
Since it is Alice’s first time using Git on her desktop machine, she first tells Git how her commits should be identified:
alice@hostA:~$ git config --global user.name "Alice Developer"alice@hostA:~$ git config --global user.email [email protected]Now, Alice needs to set up her own repository instance:
alice@hostA:~$ git clone https://git.company.com/randomCloning into 'random'...done.Alice examines the working directory:
alice@hostA:~$ cd randomalice@hostA:~/random$ ls –alFtotal 6drwxr-xr-x 1 alice staff 0 May 2 16:44 ./drwxr-xr-x 4 alice staff 0 May 2 16:39 ../drwxr-xr-x 1 alice staff 0 May 2 16:39 .git/-rw-r--r-- 1 alice staff 331 May 2 16:39 index.html-rw-r--r-- 1 alice staff 327 May 2 16:39 random.jsTip
The .git directory contains Alice’s whole copy (clone) of the repository in Git internal format and some repository-specific administrative information. See the gitrepository-layout(5) man page for details of the file layout, which can be done, for example, with the git help repository-layout command.
She wants to check the log to see the details (to examine the project history):
alice@hostA:~/random$ git logcommit 961e72b31b0d2dacc0584cbe8953c3aed1042e9b (HEAD -> master)Author: Bob Hacker [email protected]Date: Sun May 2 22:34:40 2021 +0200 Initial implementationNaming revisions
At the lowest level, a Git version identifier is a SHA-1 hash, for example, 2b953b4e80. Git supports various forms of referring to revisions, including unambiguously shortened SHA-1 (with a minimum of four characters)—see Chapter 4, Exploring Project History, for more ways.
When Alice decides to take a look at the application, she decides that using alert() to show the result is not a good user interface. To generate a new random number, the user needs to first close the window. It would be better if it was possible to generate a new result immediately.
She decides that a better solution would be to put the result on the page, below the form. She adds a single line to index.html to make a place for it:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Random Number Generator</title> <script src="random.js" defer></script></head><body><button disabled>Generate number</button><label for="max">up to</label><input type="number" id="max" name="rand_max" value="10" /><div id="result"></div></body></html>She then replaces the use of alert() in the JavaScript code by showing the result directly on the application page, using just the added <div id="result"></div> placeholder:
function getRandomInt(max) { return Math.floor(Math.random() * max) + 1;}function generateRandom() { let max = document.getElementById('max').value; let res = document.getElementById('result'); res.textContent = 'Result: ' + getRandomInt(max);}let button = document.querySelector('button');button.addEventListener('click', generateRandom);button.disabled = false;She then opens her web browser to check that it works correctly. She clicks the Generate number button a few times to check that it really generates random numbers:

Figure 1.3 – Application after Alice’s changes, with the result on the page itself
Everything looks alright, so she uses the status operation to see the pending changes:
alice@hostA:~/random$ git status -s M index.html M random.jsNo surprise here. Git knows that index.html and random.js have been modified. She wants to double-check by reviewing the actual changes with the diff command:
alice@hostA:~/random$ $ git diffdiff --git a/index.html b/index.htmlindex 1e79bb1..3021b9d 100644--- a/index.html+++ b/index.html@@ -9,5 +9,6 @@ <button disabled>Generate number</button> <label for="max">up to</label> <input type="number" id="max" name="rand_max" value="10" />+<div id="result"></div> </body> </html>diff --git a/random.js b/random.jsindex 3533d15..b036fa1 100644--- a/random.js+++ b/random.js@@ -4,7 +4,8 @@ function getRandomInt(max) { function generateRandom() { let max = document.getElementById('max').value;- alert(getRandomInt(max));+ let res = document.getElementById('result');+ res.textContent = 'Result: ' + getRandomInt(max); } let button = document.querySelector('button');Now, it’s time to commit the changes and push them to the public repository:
alice@hostA:~/random$ git commit -a -m "Show result on the page instead of using alert()"[master a030d99] Show result on the page instead of using alert() 2 files changed, 14 insertions(+), 12 deletions(-)alice@hostA:~/random$ git pushTo https://git.company.com/random.git 961e72b..a030d99 master -> masterRenaming and moving files
Section titled “Renaming and moving files”While this is happening, Bob moves on to his next task, which is to restructure the tree a bit. He doesn’t want the top level of the repository to get too cluttered, so he decides to follow one of the established conventions for the directory structure, and to move all the JavaScript source code files into the scripts/ subdirectory:
bob@hostB:~/random$ mkdir scriptsbob@hostB:~/random$ git mv *.js scripts/He then checks that everything works correctly, and it turns out that he needs to update the path to the JavaScript code in the index.html file, so he does that:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Random Number Generator</title> <script src="scripts/random.js" defer></script></head><body><button disabled>Generate number</button><label for="max">up to</label><input type="number" id="max" name="rand_max" value="10" /></body></html>He checks that everything works fine now, examines the status, and commits changes:
bob@hostB:~/random$ git status --short M index.htmlR random.js -> scripts/random.jsbob@hostB:~/random$ git commit -a -m "Directory structure"[master 1b58e54] Directory structure 2 files changed, 1 insertion(+), 1 deletion(-) rename random.js => scripts/random.js (100%)While he’s at it, to minimize the impact of reorganization on the diff output, he configures Git to always use rename and copy detection:
bob@hostB:~/random$ git config --global diff.renames copiesBob then decides the time has come to add a README.md file for the project:
bob@hostB:~/random$ git status -s?? README.mdbob@hostB:~/random$ git add README.mdbob@hostB:~/random$ git status -sA README.mdbob@hostB:~/random$ git commit -a -m "Added README.md"[master 6789f76] Added README.md 1 file changed, 3 insertions(+) create mode 100644 README.mdBob decides to rename random.js to gen_random.js:
bob@hostA:~/random$ git mv scripts/random.js scripts/gen_random.jsThis, of course, also requires changes to index.html:
bob@hostB:~/random$ git status -s M index.htmlR scripts/random.js -> scripts/gen_random.jsHe then commits those changes.
bob@hostB:~/random$ git commit -a -m "Rename random.js to gen_random.js"Updating your repository (with merge)
Section titled “Updating your repository (with merge)”Reorganization done, now Bob tries to publish those changes:
bob@hostA random$ git pushTo https://git.company.com/random ! [rejected] master -> master (fetch first)error: failed to push some refs to 'https://git.company.com/random'hint: Updates were rejected because the remote contains work that you dohint: not have locally. This is usually caused by another repository pushinghint: to the same ref. You may want to first integrate the remote changeshint: (e.g., 'git pull ...') before pushing again.hint: See the 'Note about fast-forwards' in 'git push --help' for details.But Alice was working at the same time, and she had her change ready to commit and push first. Git is not allowing Bob to publish his changes because Alice has already pushed something to the master branch, and Git is preserving her changes.
Important note
Hints and pieces of advice in Git command output will be skipped from here on for the sake of brevity.
Bob uses pull to bring in changes (as described in hint in the command output):
bob@hostB:~/random$ git pullFrom https://git.company.com/random + 3b16f17...db23d0e master -> origin/masterAuto-merging scripts/gen_random.cMerge made by the 'recursive' strategy. index.html | 1 + scripts/gen_random.js | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-)The git pull command fetched the changes, automatically merged them with Bob’s changes, and created a merge commit—opening editor to confirm committing the merge.
Important note
From version 2.31 onward, Git asks the user to set the pull.rebase configuration variable; we assume that Alice and Bob set it to false. See Chapter 9, Merging Changes Together, the Methods of combining changes section, for a more detailed description of the difference between using merge commits and using rebasing to combine changes.
Everything now seems to be good. The merge commit is done. Apparently, Git was able to merge Alice’s changes directly into Bob’s moved and renamed copy of a file without any problems. Marvelous!
bob@hostB:~/random$ git showcommit df9132d4482dfd66d6d9843db205d4e775c76509 (HEAD -> master)Merge: eabf309 a030d99Author: Bob Hacker [email protected]Date: Mon May 3 02:31:23 2021 +0200 Merge branch 'master' of https://git.company.com/randomBob checks that it works correctly (because automatically merging does not necessarily mean that the merge output is correct). It works fine and he is ready to push the merge:
bob@hostB random$ git pushTo https://git.company.com/random a030d99..df9132d master -> masterCreating a tag – a symbolic name for the revision
Section titled “Creating a tag – a symbolic name for the revision”Alice and Bob decide that the project is ready for wider distribution. Bob creates a tag so they can more easily access and refer to the released version. He uses an annotated tag for this; an often-used alternative is to use a signed tag, where the annotation contains a PGP signature (which can later be verified):
bob@hostB:~/random$ git tag -a -m "random v0.1" v0.1bob@hostB:~/random$ git tag --listv0.1bob@hostB:~/random$ git log -1 --oneline --decoratedf9132d (HEAD -> master, tag: v0.1, origin/master) Merge branch 'master' of https://git.company.com/randomOf course, the v0.1 tag wouldn’t help if it was only in Bob’s local repository. He, therefore, pushes the just-created tag:
bob@hostB random$ git push origin tag v0.1To https://git.company.com/random * [new tag] v0.1 -> v0.1Alice updates her repository to get the v0.1 tag, and to start with up-to-date work:
alice@hostA:~/random$ git pullFrom https://git.company.com/random a030d99..df9132d master -> origin/master * [new tag] v0.1 -> v0.1Updating a030d99..df9132dFast-forward README.md | 3 +++ index.html | 2 +- random.js => scripts/gen_random.js | 0 3 files changed, 4 insertions(+), 1 deletion(-) create mode 100644 README.md rename random.js => scripts/gen_random.js (100%)Resolving a merge conflict
Section titled “Resolving a merge conflict”Alice decides that it would be a good idea to add a piece of information about where the result of the random number generator would appear:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Random Number Generator</title> <script src="scripts/gen_random.js" defer></script></head><body><button disabled>Generate number</button><input type="number" id="max" name="rand_max" value="10" /><div id="result">Result:</div></body></html>Grand! Let’s see that it works correctly.

Figure 1.4 – After adding information about where the result would appear
Good. Time to commit the change:
alice@hostA:~/random$ git status -s M index.htmlalice@hostA:~/random$ git commit -a -m "index.html: Show where result goes"[master e04655f] index.html: Show where result goes 1 file changed, 1 insertion(+), 1 deletion(-)No problems here.
Meanwhile, Bob notices that if one has JavaScript disabled in the web browser or uses a text browser without support for JavaScript, the web application as it is now does not work, without explaining why. It would be a good idea to notify the user about this issue:
bob@hostB:~/random$ git pullAlready up-to-date.He decides to add a <noscript> tag to explain that JavaScript is required for the application to work:
bob@hostB:~/random$ $ git status -s M index.htmlbob@hostB:~/random$ git diffdiff --git a/index.html b/index.htmlindex 108885f..80348b7 100644--- a/index.html+++ b/index.html@@ -10,5 +10,6 @@ <label for="max">up to</label> <input type="number" id="max" name="rand_max" value="10" /> <div id="result"></div>+<noscript>To use this web app, please enable JavaScript.</noscript> </body> </html>Bob uses the w3m text-based web browser to check that <noscript> works as intended:

Figure 1.5 – Testing the application in w3m, a text-based web browser without JavaScript support
He then checks in a graphical web browser (or a live preview) that nothing changed for JavaScript-capable clients. He has his change ready to commit and push first:
bob@hostB:~/random$ git commit -a -m "Add <noscript> tag"[master a808ecf] Add <noscript> tag 1 file changed, 1 insertion(+)bob@hostB:~/random$ git pushTo https://git.company.com/random df9132d..a808ecf master -> masterSo, when Alice is ready to push her changes, Git rejects them:
alice@hostA:~/random$ git pushTo https://git.company.com/random ! [rejected] master -> master (non-fast-forward)error: failed to push some refs to 'https://git.company.com/random'Ah. Bob must have pushed a new changeset already. Alice once again needs to pull and merge to combine Bob’s changes with her own:
alice@hostA:~/random$ git pullAuto-merging index.htmlCONFLICT (content): Merge conflict in index.htmlAutomatic merge failed; fix conflicts and then commit the result.The merge didn’t go quite as smoothly this time. Git wasn’t able to automatically merge Alice’s and Bob’s changes. Apparently, there was a conflict. Alice decides to open the index.html file in her editor to examine the situation (she could have used a graphical merge tool via git mergetool instead):
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Random Number Generator</title> <script src="scripts/gen_random.js" defer></script></head><body><button disabled>Generate number</button><label for="max">up to</label><input type="number" id="max" name="rand_max" value="10" /><<<<<<< HEAD<div id="result">Result:</div>=======<div id="result"></div><noscript>To use this web app, please enable JavaScript.</noscript>>>>>>>> a808ecfb89919fd05cf50fbf879b493c83499002</body></html>Git has included both Bob’s code (between the <<<<<<<< HEAD and ======== conflict markers) and Alice’s code (between ======== and >>>>>>>>). What we want as a final result is to include both blocks of code. Git couldn’t merge it automatically because those blocks were not separated. Alice work adding Result: can be simply included right before <noscript> added by Bob. After resolving the conflict, the changes look like this:
alice@hostA:~/random$ $ git diffdiff --cc index.htmlindex ea1a830,80348b7..0000000--- a/index.html+++ b/index.html@@@ -9,7 -9,6 +9,6 @@@ <button disabled>Generate number</button> <label for="max">up to</label> <input type="number" id="max" name="rand_max" value="10" /> -<div id="result"></div> +<noscript>To use this web app, please enable JavaScript.</noscript>+ <div id="result">Result:</div> </body> </html>That should take care of the problem. Alice refreshes the web application in a web browser to check that it works correctly. She marks the conflict as resolved and commits changes:
alice@hostA:~/random$ git status -sUU index.htmlalice@hostA:~/random$ git commit -a -m 'Merge: mark output + noscript'[master 919f0f7] Merge: mark output + noscriptAnd then she retries the push:
alice@hostA:~/random$ git pushTo https://git.company.com/random a808ecf..919f0f7 master -> masterAnd… done.
Adding files in bulk and removing files
Section titled “Adding files in bulk and removing files”Bob decides to add a COPYRIGHT file with a copyright notice for the project. There was also a NEWS file planned (but not created), so he uses a bulk add to add all the files:
bob@hostB:~/random$ git add -vNothing specified, nothing added.Maybe you wanted to say 'git add .'?bob@hostB:~/random$ git add -v .add 'COPYRIGHT'add 'COPYRIGHT~'Oops! Because Bob didn’t configure his ignore patterns, the backup file, COPYRIGHT~, was caught too (such a system-specific pattern should go to the repository’s .git/info/exclude or personal ignore file, ~/.config/git/ignore, as described in Chapter 3, Managing Your Worktrees, in the Ignoring files section). Let’s remove this file:
bob@hostB:~/random$ git status -sA COPYRIGHTA COPYRIGHT~bob@hostB:~/random$ git rm COPYRIGHT~error: the following file has changes staged in the index: COPYRIGHT~(use --cached to keep the file, or -f to force removal)bob@hostB:~/random$ git rm -f COPYRIGHT~rm 'COPYRIGHT~'Let’s check the status and commit the changes:
bob@hostB:~/random$ git status -sA COPYRIGHTbob@hostB:~/random$ git commit -a -m 'Added COPYRIGHT'[master ca3cdd6] Added COPYRIGHT 1 files changed, 2 insertions(+), 0 deletions(-) create mode 100644 COPYRIGHTUndoing changes to a file
Section titled “Undoing changes to a file”A bit bored, Bob decides that their web application looks bland, and adds the Bootstrap CSS library (https://getbootstrap.com) to the index.html header:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">He checks how much source code it changed:
bob@hostB:~/random$ git diff --statindex.html | 4 ++++ 1 file changed, 4 insertions(+)That looks all right; however, the application doesn’t look that much better without further changes, and now it requires access to the internet. Bob decides that it is not the time to move to the Bootstrap CSS framework, and undoes the changes to index.html:
bob@hostB:~/random$ git status -s M index.htmlbob@hostB:~/random$ git restore index.htmlbob@hostB:~/random$ git status -sIf you can’t remember how to revert a particular type of change or to update what is to be committed (using git commit without -a), the output of git status (without -s) contains information about what commands to use. This is shown in the following example:
bob@hostB:~/random$ git statusOn branch masterYour branch is ahead of 'origin/master' by 1 commit. (use "git push" to publish your local commits)Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git restore <file>..." to discard changes in working directory) modified: index.htmlno changes added to commit (use "git add" and/or "git commit -a")Branching and merging
Section titled “Branching and merging”Developers often need to isolate a specific set of changes that is expected to not be ready for some time, to create another line of development: a branch. Usually, when the mentioned set of changes is ready, you would then want to join those branches, which can be done with a merge operation.
Creating a new branch
Section titled “Creating a new branch”Alice decides that it would be a good idea to provide a way for the user to configure the lower bound of the range the random number is chosen from (currently set to 1)—that is, make both the minimum and maximum of the generated number configurable.
She needs to add a new input to the index.html file. Alice notices that labels for inputs need to be adjusted, too:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Random Number Generator</title> <script src="scripts/gen_random.js" defer></script></head><body><button disabled>Generate number</button><label for="min">between</label><input type="number" id="min" name="rand_min" value="1" /><label for="max">and</label><input type="number" id="max" name="rand_max" value="10" /><div id="result">Result:</div><noscript>To use this web app, please enable JavaScript.</noscript></body></html>Then, Alice needs to adjust the JavaScript code to read another input and to generate a random integer between two given values, inclusive:
function getRandomIntInclusive(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1) + min);}function generateRandom() { let min = document.getElementById('min').value; let max = document.getElementById('max').value; let res = document.getElementById('result'); res.textContent = 'Result: ' + getRandomIntInclusive(min, max);}let button = document.querySelector('button');button.addEventListener('click', generateRandom);button.disabled = false;Alice then checks that everything works correctly:

Figure 1.6 – Upper and lower bounds are made configurable
However, during testing, she notices that the application does not ensure that the minimum is smaller than or equal to the maximum value, and does not behave correctly if the input’s order is switched.
She decides to try to fix this issue. However, to make each commit small and self-contained, ensuring that the application works sanely in such cases (when, for example, the user provides 10 and 5 as the minimum and maximum, respectively) will be done as a separate change.
To isolate this line of development from other changes and prevent integrating the feature that is not fully ready, she decides to create her own branch named ’ min-max' (see also Chapter 8, Advanced Branching Techniques), and switch to it:
alice@hostA:~/random$ git checkout -b min-maxSwitched to a new branch 'min-max'alice@hostA:~/random$ git branch master* min-maxTip
Instead of using the git checkout –b min-max or git switch --create min-max shortcut to create a new branch and switch to it in one command invocation, Alice could have first created a branch with git branch min-max, then switched to it with git switch min-max.
She commits her changes and pushes them, knowing that the push will succeed because she is working on her private branch:
alice@hostA:~/random$ git commit -a -m 'Make lower bound configurable'[min-max 2361cfc] Make lower bound configurable 2 files changed, 9 insertions(+), 4 deletions(-)alice@hostA:~/random$ git pushfatal: The current branch min-max has no upstream branch.To push the current branch and set the remote as upstream, use git push --set-upstream origin min-maxAlright! Git just wants Alice to set up a remote origin as the upstream for the newly created branch (it is using a simple push strategy); this will also push this branch explicitly:
alice@hostA:~/random$ git push --set-upstream origin min-maxTo https://git.company.com/random* [new branch] min-max -> min-maxBranch 'min-max' set up to track remote branch 'min-max' from 'origin'.Tip
If she wants to make her branch visible but private (so nobody but her can push to it), she needs to configure the server with hooks or use Git repository management software such as gitolite to manage it for her.
Merging a branch (no conflicts)
Section titled “Merging a branch (no conflicts)”Meanwhile, over in the default branch, Bob decides to push his changes by adding the COPYRIGHT file:
bob@hostB random$ git pushTo https://git.company.com/random ! [rejected] master -> master (fetch first)[…]OK. Alice was busy working at making the minimum value of the range configurable to choose random integers from (and resolving a merge conflict), and she pushed her changes first:
bob@hostB:~/random$ git pullFrom https://git.company.com/random a808ecf..919f0f7 master -> origin/master * [new branch] min-max -> origin/min-maxGit then opens the editor with the commit message for the merge. Bob exits the editor to confirm the default description:
Merge made by the 'recursive' strategy. index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)Well, Git has merged Alice’s changes cleanly, but there is a new branch present. Let’s take a look at what is in it, showing only those changes exclusive to the min-max branch (the double-dot syntax is described in Chapter 4, Exploring Project History):
bob@hostB:~/random$ git log HEAD..origin/min-maxcommit 2361cfc062809d96b9a04d8032b9c433cae5c350 (origin/min-max)Author: Alice Developer <[email protected]>Date: Mon May 3 14:35:33 2021 +0200 Make lower bound configurableInteresting! Bob decides he wants that. So, he asks Git to merge stuff from Alice’s branch (which is available in the respective remote tracking branch) into the default branch:
bob@hostB:~/random$ git merge origin/min-maxMerge made by the 'recursive' strategy. index.html | 4 +++- scripts/gen_random.js | 9 ++++++--- 2 files changed, 9 insertions(+), 4 deletions(-)Undoing an unpublished merge
Section titled “Undoing an unpublished merge”Bob realizes that it should be up to Alice to decide when the feature is ready for inclusion (and hears that it is not ready yet). He decides to undo a merge. Because it is not published, it is as simple as rewinding to the previous state of the current branch:
bob@hostB:~/random$ git reset --hard @{1}HEAD is now at 02ad67e Merge branch 'master' of https://git.company.com/randomImportant note
This example demonstrates the use of the reflog for undoing operations; another solution would be to go to a previous (pre-merge) commit following the first parent, with HEAD^ instead of @{1}.
Bob then pushes his changes.
Summary
Section titled “Summary”This chapter walked us through the process of working on a simple example project by a small development team.
We have recalled how to start working with Git, either by creating a new repository or by cloning an existing one. We have seen how to prepare a commit by adding, editing, moving, and renaming files, how to revert changes to the file, how to examine the current status and view changes to be committed, and how to tag a new release.
We have recalled how to use Git to work at the same time on the same project, how to make our work public, and how to get changes from other developers. Though using a version control system helps with simultaneous work, sometimes Git needs user input to resolve conflicts in work done by different developers. We have seen how to resolve a merge conflict.
We have recalled how to create a tag marking a release, and how to create a branch starting an independent line of development. Git requires tags and new branches to be pushed explicitly, but it fetches them automatically. We have seen how to merge a branch.
The next chapter will cover creating new revisions and new lines of development in much more detail, and it will introduce and explain the concept of the staging area for commits.
Questions
Section titled “Questions”Answer the following questions to test your knowledge of this chapter:
- Describe how to create a repository from existing files and how to get your own copy of an existing repository.
- Describe how to create a new version of the project locally, and how to publish those changes.
- Explain how to get changes from other developers, and how to combine those changes.
- What do merge conflict markers look like, and how can you resolve a merge conflict?
- What can you do to make Git not show temporary backup files as unknown files in the status output? What about the products and byproducts of the build system?
- Where can you find information about how to undo adding a file, or how to undo changes to a file?
- How can you abandon the commit? What are the dangers of doing so?
- Explain how Git manages moving, copying, and renaming files.
Answers
Section titled “Answers”Here are the answers to the questions given above:
- Use
git init,git add ., andgit committo create a repository from existing files. Usegit cloneto get your own copy of the existing repository. - Use
git commitorgit commit -ato create a new revision, and usegit pushto publish changes. - Use
git fetchto get updates from other developers, orgit pullto get updates and merge them together. Usegit merge(or, as mentioned in later chapters,git rebase) to combine changes. - Merge conflicts are presented using the
<<<<<<<,=======, and>>>>>>>markers; you can also find the|||||||marker used, depending on the configuration. To resolve the conflicts, you need to edit files marked as conflicting into shape, usegit addon them when finished, and then finalize the merge withgit commitorgit merge --continue(or rebase withgitrebase --continue). - To make Git ignore specific types of files, you need to add appropriate glob patterns to one of the
ignorefiles. It is a good practice to ignore byproducts of the build system and other generated files using the.gitignorefile and add patterns for temporary files specific to one’s individual choice to a per-repository (.git/info/ignore) or per-userignorefile. - All information about how to undo adding, removing, or staging a file can be found in the
gitstatusoutput. - You can abandon a commit with
git reset --hard HEAD^, but it may lead to losing your changes (you can recover committed changes with the help of reflog if it did not expire; uncommitted changes are lost forever). - Git handles code movement, such as renaming, moving, and copying files, by using rename detection during merging and
diffgeneration.
Further reading
Section titled “Further reading”If you need a reminder about Git basics, the following references might help you.
- Everyday Git With 20 Commands or So, part of the Git documentation as
giteveryday(7): https://git-scm.com/docs/giteveryday - A tutorial introduction to Git, part of the Git documentation as
gittutorial(7): https://git-scm.com/docs/gittutorial - The Git User’s Manual, part of the Git documentation: https://git-scm.com/docs/user-manual
- Eric Sink, Version Control by Example, Pyrenean Gold Press (2011): https://ericsink.com/vcbe/index.html
- Scott Chacon and Ben Straub, Pro Git, 2nd Edition, Apress (2014): https://git-scm.com/book/en/v2