Developing with Git
local graph
Chapter 2 — Developing with Git
Section titled “Chapter 2 — Developing with Git”This chapter will describe how to create new revisions and new lines of development (new branches) with Git.
Here, we will focus on committing one’s own work on the solo development. The description of working as one of the contributors is left for Chapter 6, Collaborative Development with Git, while Chapter 9, Merging Changes Together, will show how to join created lines of development and how Git can help in maintainer duties.
This chapter will introduce the very important Git concept of the staging area (also called the index), while more advanced techniques for manipulating it will be described in Chapter 3, Managing Your Worktrees. It will also explain, in detail, the idea of a detached HEAD — that is, an anonymous, unnamed branch. Here, you can also find how Git describes differences between two versions of the project, or changes to the project, including a detailed description of the so-called extended unified diff format.
The following is the list of the topics we will cover in this chapter:
- The index — a staging area for commits
- Examining the status of the working area, and changes in it
- How to read the extended unified diff that is used to describe changes
- Selective and interactive commit, and amending a commit
- Creating, listing, renaming, and switching to branches, and listing tags
- What can prevent switching branches, and what you can do then
- Rewinding a branch with
git reset - Detached
HEAD— that is, the unnamed branch (for example, a result of checking out a tag)
Creating a new commit
Section titled “Creating a new commit”Before starting to develop with Git, you should introduce yourself with a name and an email, as shown in Chapter 1, Git Basics in Practice. This information will be used to identify your work, either as an author or as a committer. The setup can be global for all your repositories (with git config --global, or by editing the ~/.gitconfig file directly), or local to a repository (with git config, or by editing the .git/config file inside the given repository). The per-repository configuration overrides the per-user one (you will learn more about this in Chapter 13, Customizing and Extending Git).
Multiple identities
You might want to use your company email for work repositories, but your own, non-work email for public repositories you work on. This can be done by setting one identity globally (for the user) and using the local repository config for setting an alternate identity for exceptions. Another possible solution would be to use conditional includes with the includeIf section, using it to include appropriate configuration files with per-directory identities.
The relevant fragment of the appropriate config file could look like the following example:
[user] name = Joe R. Hacker email = [email protected]How a new commit extends a project’s history
Section titled “How a new commit extends a project’s history”Contributing to the development of a project usually consists of creating new revisions of said project. To mark the current state of the project as a new version, you use the git commit command. Git will then ask for a description of changes (commit message), and then extend the project history with the newly created revision. Here’s what is happening behind the curtain — it’s useful to understand this to better use advanced Git techniques.
In Git, the history of the project is stored as a graph of revisions (versions), where each revision points to the previous version it was based on. The git commit command simply creates a new node in this graph (a commit node), extending it.
To know where each branch is, Git uses branch HEAD as a reference to the graph of revisions. The HEAD denotes which branch is the current branch — that is, on which branch to create new commits at a given point in time.
You can find out more about the concept of the Directed Acyclic Graph (DAG) of revisions in Chapter 4, Exploring Project History. Creating a new commit adds a new node to the graph of revisions, and adjusts the position of branch tips (heads), as shown on the following figure.

Figure 2.1 – The graph of revisions for an example project, before and after creating a new commit on the “master” branch
Let’s assume that we are on the master branch and that we want to create a new version (the details of this operation will be described in more detail later). The git commit command will create a new commit object — a new revision node. This commit will have the checked-out revision (c7cd3 in the example in Figure 2*.1*) as the previous node (as a parent).
That revision is found by following references starting from HEAD; here, it is a chain starting at HEAD, then following to master, and finally arriving at c7cd3.
Then, Git will create a new commit node, a3b79, and then move the master pointer to that new node. In Figure 2*.1*, the new commit is marked with a thick red outline. Note that the HEAD pointer doesn’t change; all the time, it points to master. The performed commit operation is logged in the reflog for the master branch and for HEAD (current branch); one can examine this log with the git reflog master or git reflog HEAD command.
The index — a staging area for commits
Section titled “The index — a staging area for commits”Each of the files inside the working area of the Git repository can at a given point in time be either known or unknown to Git — that is, version-controlled or not. Any file known to Git is also known as a tracked file. The files unknown to Git can be either untracked or ignored (you can find more information about ignoring files in Chapter 3, Managing Your Worktrees). You can make an unknown file become tracked with the git add command.
Files tracked by Git are usually in either of the two states: committed (or unchanged) or modified. The committed state means that the file contents in the working directory are the same as in the last release (HEAD), which is safely stored in the repository. The file is modified if it has changed compared to the last committed version, which means it is different than in HEAD.
However, in Git, there are other states possible. Let’s consider what happens when we use the git add command to add a file that was previously unknown to Git (an untracked file), but before creating a new commit that adds this file. A version control system needs to store somewhere the information that the given file is to be included in the next commit. Git uses something called the index for this; it is the staging area that stores information that will go into the next commit. The git add <file> command stages the current contents (current version) of the file, adding it to the index.
Important note
If you want to only mark a file for the addition, you can use git add -N <file> or git add --intent-to-add <file>; these commands simply stage the empty contents for a file (<file> here is a placeholder for the file’s name).
The staging area stores the state of the project. It is the third such section, after a working directory (which contains your own copy of the project files and is used as a private isolated workspace to make changes) and a local repository (which stores your own copy of the project history and is used to synchronize changes with other developers). Figure 2*.2* shows how you can interact with these three sections, specifically in the context of creating a new commit:

Figure 2.2 – The working directory, the staging area, and the local git repository, creating a new commit
The arrows on this diagram show how the Git commands copy contents. For example, git add takes the content of the file from the working directory and puts it into the staging area. Creating a new commit requires, explicitly or implicitly, the following steps:
- You make changes to files in your working directory, usually modifying them using your favorite editor.
- You stage the files, adding snapshots of them (their current contents) to your staging area, usually with the
gitaddcommand. - You create a new revision with the
git commitcommand, which takes the files as they are in the staging area and stores that snapshot permanently in your local repository.
In the beginning, and usually just after the commit (unless it was a selective commit), the tracked files are identical in the working directory, in the staging area, and in the last commit (in the committed version, that is HEAD).
Examining the staged file contents and the committed file contents
To examine the working directory state of a file, you can simply open it in an editor, or (on Linux or in Git Bash) simply use cat <filename>; examining other stages is more involved. To see the state in the staging area, you can use the git show :<filename> command. To see the committed version, use the git show <revision>:<filename> command (where <revision> may be HEAD). Here, a filename starting with ./ or ../ denotes that the path is relative to the current directory; otherwise, it is taken to be relative to the top-level directory of the repository you are in.
Often, however, one would use a special shortcut, the git commits -a command (spelled as git commit --all in the long form), which would take all the changed tracked files, add them to the staging area, and create a new commit (see Figure 2*.2*). This command gives the same result as running git add --update, followed by a git commit command. Note that the new files still need to be explicitly added using git add to be tracked and included in new commits.
Examining the changes to be committed
Section titled “Examining the changes to be committed”Before committing to the changes and creating a new revision (a new commit), you would want to see what you have done.
Git adds the information about the changes to be committed to the commit message template, which is then passed to the editor, and you will see this when writing the commit message. This is, of course, unless you specify the commit message on the command line — for example, with git commit -m "Short description". The commit message template in Git is configurable (refer to Chapter 13, Customizing and Extending Git, for more information).
Important note
You can always abort creating a commit by exiting the editor without any changes, or with an empty commit message (comment lines — that is, lines beginning with # — do not count). If you want to create a commit with an empty commit message, you need to use the -- allow-empty-message option.
In most cases, you would want to examine pending changes for correctness before creating a commit.
The status of the working directory
Section titled “The status of the working directory”The main tool you use to examine which files are in which state — that is, which files have changed, whether there are any new files, and so on — is the git status command.
The default output is explanatory and quite verbose. If there are no changes, for example, directly after cloning, you could see something like this:
$ git statusOn branch masternothing to commit, working tree cleanIf the current branch (which, in this example, is the master branch) is a local branch intended to create changes that are to be published and to appear in the public repository, and is configured to track its upstream branch, origin/master, you would also see the information about the tracked branch:
Your branch is up to date with 'origin/master'.In further examples in this chapter, we will ignore it and not include the information about branches and tracking branches.
Let’s say you have added two new files to your project: a COPYING file with the copyright and license, and a NEWS file, which is currently empty. In order to begin tracking a new COPYING file, you used git add COPYING. Accidentally, you removed the README file from the working directory with rm README. You also modified the Makefile and renamed rand.c to random.c with git mv without modifying the file.
The default long format is designed to be human-readable, verbose, and descriptive:
$ git statusOn branch masterChanges to be committed: (use "git restore --staged <file>..." to unstage) new file: COPYING renamed: src/rand.c -> src/random.cChanges 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: Makefile deleted: READMEUntracked files: (use "git add <file>..." to include in what will be committed) NEWSOlder versions of Git will suggest using different commands than git restore.
As you can see, Git not only describes which files have changed but also explains how to change their status — either include it in the commit or remove it from the set of pending changes (more information about commands shown in the git status output can be found in Chapter 3, Managing Your Worktrees). There are up to three sections present in the output:
- Changes to be committed: This section is about the staged changes that would be committed with
git commit(without the-a/--alloption). It lists files whose snapshot in the staging area is different from the version from the last commit (HEAD). - Changes not staged for commit: This section lists the files whose working directory contents are different from their snapshots in the staging area. Those changes would not be committed with
git commit, but would be committed withgit commit -aas changes in the tracked files. - Untracked files: This lists the files, unknown to Git, that are not ignored (refer to Chapter 3, Managing Your Worktrees for how to use gitignores to make files be ignored). These files would be added with the bulk add command,
git add ., if run in the top directory of the project. You can skip this section with the--untracked-files=no(-unofor short) option.
If the section does not contain any files, it will be not shown. Note also that the file may appear in more than one section. For example, a new file that got added with git add and then modified would appear in both Changes to be committed and Changes not staged for commit.
One does not need to make use of the flexibility that the explicit staging area gives; one can simply use git add just to add new files and git commit –a to create the commit from changes to all tracked files. In this case, you would create a commit from both the Changes to be committed and Changes not staged for commit sections.
There is also a terse --short output format for git status. Its --porcelain version is suitable for scripting because it is promised to remain stable, while --short is intended for user output, uses color if possible, and could change in the future. For the same set of changes, this output format would look something like the following:
$ git status --shortA COPYING M Makefile D READMER src/rand.c -> src/random.c?? NEWSIn this format, the status of each path is shown using a two-letter status code. The first letter shows the status of the index (the difference between the staging area and the last commit), and the second letter shows the status of the worktree (the difference between the working area and the staging area):
| Symbol | Meaning |
|---|---|
| (a space) | Not updated/unchanged |
| M | M odified (updated) |
| A | A dded |
| D | D eleted |
| R | R enamed |
| C | C opied |
Table 2.1 – Letter status codes used in the short format of the git-status command
Not all combinations are possible. Status letters A, R, and C are possible only in the first column, for the status of the index.
A special case, ??, is used for the unknown (untracked) files, and !! for ignored files (when using git status -- short --ignored).
Note about status codes
All the possible outputs are described here; the case where we have just done a merge that resulted in merge conflicts is not shown in Table 2.1 but is left to be described in Chapter 9, Merging Changes Together.
Examining differences from the last revision
Section titled “Examining differences from the last revision”If you want to know not only which files were changed (which you get with git status), but also what exactly you have changed, you can use the git diff command:

Figure 2.3 – Examining the differences between the working directory, the staging area, and the local Git repository
In the last section, we learned that in Git, there are three stages: the working directory, the staging area, and the repository (usually the last commit). Therefore, we have not one set of differences, but three, as shown in Figure 2*.3*. You can ask Git the following questions:
- What have you changed but not yet staged — that is, what are the differences between the staging area and the working directory?
- What have you staged that you are about to commit — that is, what are the differences between the last commit (
HEAD) and the staging area? - What changes have you made to the files in the working directory since the last commit (
HEAD)?
To see what you’ve changed but not yet staged, type git diff with no other arguments. This command compares what is in your working directory to what is in your staging area. These are the changes that could be added but wouldn’t be present if we created a commit with git commit (without -a); those changes are listed in the Changes not staged for commit section in the git status output.
To see what you’ve staged that will go into your next commit, use git diff --staged (or git diff --cached). This command compares what is in your staging area to the content of your last commit. These are the changes that would be added with git commit (without -a) — Changes to be committed in the git status output. You can compare your staging area to any commit with git diff --staged <commit>; HEAD (the last commit) is just the default.
You can use git diff HEAD to compare what is in your working directory to the last commit (or arbitrary commit with git diff <commit>). These are the changes that would be added with the git commit - a shortcut.
If you are using git commit –a and not making use of the staging area, usually, it is enough to use git diff to examine the changes that will land in the next commit. The only issue is the new files that are added with bare git add; they won’t show in the git diff output unless you use git add --intent-to-add (or its equivalent git add -N) to add new files.
Unified Git diff format
Section titled “Unified Git diff format”Git, by default, and in most cases, will show the changes in the unified diff output format. Understanding this output is very important, not only when examining changes to be committed, but also when reviewing and examining changes. This may happen, for example, during the code review, or when finding bugs after git bisect has found the suspected commit.
Different ways of examining differences
You can request only statistics of changes with the --stat or --dirstat option, just names of the changed files with --name-only, filenames with the type of changes with --name-status, a tree-level view of changes with --raw, or a condensed summary of extended header information with --summary (see later for an explanation of what “extended header” means and what information it contains). You can also request word diff rather than line diff with --word-diff, though this changes only the description of changes; headers and hunk headers remain similar.
Diff generation can also be configured for specific files or types of files with appropriate gitattributes. You can specify an external diff helper — that is, the command that describes the changes — or you can specify a text conversion filter for binary files (you will learn more about this in Chapter 3, Managing Your Worktrees).
If you prefer to examine the changes in a graphical tool (which usually provides side-by-side diff), you can do it by using git difftool instead of git diff. You can specify the tool with the --tool=<tool> option or with the diff.tool configuration variable. If the tool you use is not supported by Git or is not in PATH, this may require some configuration. Using external tools with Git like this will be explained in more detail in Chapter 13, Customizing and Extending Git.
Let’s look at an example of an advanced diff from Git project history, using the diff from the 1088261f commit from the git.git repository. You can view these changes in a web browser — for example, on GitHub; this is the third patch in this commit, https://github.com/git/git/commit/1088261f6fc90324014b5306cca4171987da85:
diff --git a/builtin-http-fetch.c b/http-fetch.csimilarity index 95%rename from builtin-http-fetch.crename to http-fetch.cindex f3e63d7206..e8f44babd9 100644--- a/builtin-http-fetch.c+++ b/http-fetch.c@@ -1,8 +1,9 @@ #include "cache.h" #include "walker.h"-int cmd_http_fetch(int argc, const char **argv, const char *prefix)+int main(int argc, const char **argv) {+ const char *prefix; struct walker *walker; int commits_on_stdin = 0; int commits;@@ -18,6 +19,8 @@ int cmd_http_fetch(int argc, const char **argv, int get_verbosely = 0; int get_recover = 0;+ prefix = setup_git_directory();+ git_config(git_default_config, NULL); while (arg < argc && argv[arg][0] == '-') {Let’s analyze this patch line by line. The first line, diff --git a/builtin-http-fetch.c b/http-fetch.c, is a git diff header in the form diff --git a/file1 b/file2. The a/ and b/ filenames are the same unless rename or copy operation is involved (such as in our case), even if the file is added or deleted. The --git option means that the diff is in the git diff output format.
The next lines are one or more extended header lines. The first three lines in this example tell us that the file was renamed from builtin-http-fetch.c to http-fetch.c and that these two files are 95% identical (information that was used to detect this rename):
similarity index 95%rename from builtin-http-fetch.crename to http-fetch.cImportant note
Extended header lines describe information that cannot be represented in an ordinary unified diff, except for information that the file was renamed. Besides a similarity or dissimilarity score, like in this example, those lines can also describe the changes in file type (such as from a non-executable to an executable file).
The last line in the extended diff header, in this example, is as follows:
index f3e63d7206..e8f44babd9 100644The preceding code tells us about the mode (permissions) of a given file. Here, 100644 means that it is an ordinary file and not a symbolic link, and that it hasn’t set the executable permission bit (these three are the only file permissions tracked by Git). This line also tells us about the shortened hash of the pre-image (the version of the file before the given change, f3e63d7206 here) and post-image (the version of the file after the change, e8f44babd9 here). This line is used by git am --3way to try to do a three-way merge if the patch cannot be applied itself. For the new files, the pre-image hash is 0000000000; it’s the same for the deleted files with the post-image hash.
Next is the unified diff header, which consists of two lines:
--- a/builtin-http-fetch.c+++ b/http-fetch.cCompared to the diff -U result, it doesn’t have a from-file modification time or a to-file modification time. Those should be present after the space just after the source (pre-image) and the destination or the target (post-image) filenames. If the file was created, the source would be /dev/null; if the file was deleted, the target would be /dev/null.
Tip
If you set the diff.mnemonicPrefix configuration variable to true in place of the a/ prefix for the pre-image and b/ for the post-image in this two-line header, you would instead have the c/ prefix for commit, i/ for index, w/ for worktree, and o/ for object, respectively, to show what you’re comparing This makes it easy to distinguish sides in git diff, git diff --cached, git diff HEAD output, and so on.
Next comes one or more change hunks, or hunks of differences; each hunk shows one area where the files differ. Unified format hunks start with the line describing where the changes were in the file, called the hunk header, as follows:
@@ -1,8 +1,9 @@This line matches the following format pattern: @@ from-file-range to-file-range @@. The from-file range is in the form -<start line>,<number of lines >, and the to-file range is +<start line>,<number of lines>. Both start line and number of lines refer to the position and length of the hunk in the pre-image and post-image, respectively. If number of lines is not shown, it means that it is 0.
In this example, we can see that the changes begin at the first line of the file, both in the pre-image (file before the changes) and post-image (file after the changes). We also see that the fragment of code corresponding to this hunk of diff has eight lines in the pre-image and nine lines in the post-image. This difference in the number of lines means that one line is added. By default, Git will also show three unchanged lines surrounding changes (three so-called context lines).
Git will also show the “ function name ” where each change occurs (or equivalent, if any, for other types of files; this can be configured with .gitattributes via diff driver —see Chapter 3, Managing Your Worktrees, in the Configuring diff output section in File attributes); it is like the -p option in GNU diff:
@@ -18,6 +19,8 @@ int cmd_http_fetch(int argc, const charGit includes many builds in patterns for extracting the “ function ” heading for the hunk for various programming languages.
Next is the description of where and how files differ. The lines common to both files are prefixed with a space “ (" ") ” indicator character. The lines that differ between the two files have one of the following indicator characters in the left print column:
- +: A line was added here to the second file
- -: A line was removed here from the first file
Note
In the plain word-diff format, instead of comparing file contents line by line, added words are surrounded by {+ and +} and removed words by [- and -], as in the following example:
int [-cmd_http_fetch-]{+main+}(int argc, const char **argv[-, const char *prefix-])If the last hunk includes, among its lines, the very last line of either version of the file, and that last line is incomplete line (which means that the file does not end with the end-of-line character at the end of the hunk), you will find the following:
\ No newline at end of fileThis situation is not present in the example used.
So, for the example used here, the first hunk means that cmd_http_fetch was replaced by main and the const char *prefix; line was added:
#include "cache.h" #include "walker.h"-int cmd_http_fetch(int argc, const char **argv, const char *prefix)+int main(int argc, const char **argv) {+ const char *prefix; struct walker *walker; int commits_on_stdin = 0; int commits;See how for the replaced line, the old version of the line appears as removed (-) and the new version as added (+).
In other words, before the change, the appropriate fragment of the file, which was then named builtin-http-fetch.c, looked similar to the following code fragment:
#include "cache.h"#include "walker.h"int cmd_http_fetch(int argc, const char **argv, const char *prefix){ struct walker *walker; int commits_on_stdin = 0; int commits;After the change, this fragment of the file, which is now named http-fetch.c, looks similar to the following instead:
#include "cache.h"#include "walker.h"int main(int argc, const char **argv){ const char *prefix; struct walker *walker; int commits_on_stdin = 0; int commits;Selective commit
Section titled “Selective commit”Sometimes, after examining the pending changes as explained, you realize that you have two (or more) unrelated changes in your working directory that should belong to two different logical changes; such a problem is sometimes called the tangled working copy problem. You need to put those unrelated changes into separate commits as separate changesets. This is the type of situation that can occur even when trying to follow best practices (see Chapter 15, Git Best Practices).
One solution is to create the commit as-is and fix it later (split it in two). You can read about how to do this in Chapter 10, Keeping History Clean.
Sometimes, however, some of the changes are needed now and must be shipped immediately (for example, a bugfix to a live website), while the rest of the changes are not ready yet (they are a work in progress). You need to tease those changes apart into two separate commits.
Selecting files to commit
Section titled “Selecting files to commit”The simplest situation is when these unrelated changes touch different files. For example, if the bug was in the view/entry.tmpl file and the bugfix changes only this file (and there were no other changes to this file, unrelated to fixing the bug), you can create a bugfix commit with the following command:
$ git commit view/entry.tmplThis command will ignore changes staged in the index (what was in the staging area), and instead record the current contents of a given file or files (what is in the working directory).
Interactively selecting changes
Section titled “Interactively selecting changes”Sometimes, however, the changes cannot be separated in this simple way; the changes to the file are tangled together. You can try to tease them apart by giving the - - interactive option to the git commit command:
$ git commit --interactive staged unstaged path 1: unchanged +3/-2 Makefile 2: unchanged +64/-1 src/rand.c*** Commands *** 1: status 2: update 3: revert 4: add untracked 5: patch 6: diff 7: quit 8: helpWhat now>Here, Git shows us the status and the summary of changes to the working area (unstaged) and the staging area (staged), which is also the output of the status subcommand. The changes are described by the number of added and deleted lines — for example, +3/-2 here (this is similar to what the git diff --numstat command would show).
Tip
It might be easier to use a graphical tool such as git gui with this capability. In GUIs, such as the one mentioned, one can use the mouse to select which lines of changes to include or exclude.
You can use the help subcommand, accessed by pressing h, to check what those listed operations mean:
What now> hstatus - show paths with changesupdate - add working tree state to the staged set of changesrevert - revert staged set of changes back to the HEAD versionpatch - pick hunks and update selectivelydiff - view diff between HEAD and indexadd untracked - add contents of untracked files to the staged set of changesTo tease apart changes, you need to choose the patch subcommand (for example, with 5 or p). Git will then ask for the files with the Update>> prompt; you then need to select the files to selectively update with their numeric identifiers, as shown in the status, and type return. You can type * to select all the files possible. After making the selection, end it by answering with an empty line:
What now> p staged unstaged path 1: unchanged +3/-2 Makefile 2: unchanged +64/-1 src/rand.cPatch update>> 1 staged unstaged path* 1: unchanged +3/-2 Makefile 2: unchanged +64/-1 src/rand.cPatch update>>You can skip directly to patching files by using git commit --patch instead of git commit - - interactive.
Git will then display all the changes to the specified files on a hunk-by-hunk basis, and let you choose, among others, one of the following options for each hunk:
y - stage this hunkn - do not stage this hunkq - quit; do not stage this hunk or any of the remaining onesa - stage this hunk and all later hunks in the file…s - split the current hunk into smaller hunkse - manually edit the current hunk? - print helpThe hunk output and the prompt look similar to the following:
@@ -16,7 +15,6 @@ int main(int argc, char *argv[]) int max = atoi(argv[1]);+ srand(time(NULL)); int result = random_int(max); printf("%d\n", result);Stage this hunk [y,n,q,a,d,/,j,J,g,e,?]? yIn many cases, it is enough to simply select which of those hunks of changes you want to have in the commit. In extreme cases, you can split a chunk into smaller pieces, or even manually edit the difference.
Many graphical tools, including git gui, also allow for the interactive selection of changes going to the next commit. You can find out more in Chapter 13, Customizing and Extending Git, in the Graphical interfaces section.
Creating a commit step by step
Section titled “Creating a commit step by step”Using git commit --interactive to select changes to a commit doesn’t, unfortunately, allow you to test the changes to be committed. You can always check that everything works after creating a commit (that is, compile the code and/or run tests), and then amend it if there are any errors (see the next section, Amending a commit). There is, however, an alternative solution.
Instead of using the interactive commit feature, you can prepare to commit by putting the pending changes into the staging area with git add --interactive or an equivalent solution (such as a graphical commit tool for Git — for example, git gui). The interactive commit is just a shortcut for interactive add followed by commit. Then, you should examine these changes with git diff --cached, modifying them as appropriate with git add <file>, git checkout <file >, and git reset <file>.
In theory, you should also test whether these changes are correct, checking that at least they do not break the build. To do this, first use git stash save --keep-index to save the current state and bring the working directory to the state prepared in the staging area (the index). After this command, you can run tests (or at least check whether the program compiles and doesn’t crash). If tests pass, you can then run git commit to create a new revision. If tests fail, you should restore the working directory while keeping the staging area state with the git stash pop --index command; it might be required to precede it with git reset --hard. The latter might be needed because Git is overly conservative when preserving your work and does not know that you have just stashed. First, there are uncommitted changes in the index that prevent Git from applying the stash, and second, the changes to the working directory are the same as those stashed, so, of course, they would conflict.
You can find more information about stashes, including how they work, in Chapter 3, Managing Your Worktrees, in the Stashing away your changes section.
Amending a commit
Section titled “Amending a commit”One of the better things about Git is that you can undo almost anything; you only need to know how to. This is because no matter how carefully you craft your commits, sooner or later, you’ll forget to add a change or mistype the commit message. That’s when the --amend flag of the git commit command comes in handy; it allows you to change the very last commit really easily. Note that with git commit -- amend, you can also amend the merge commits (for example, to fix a merging error). Figure 2*.4* shows how this amend operation changes the graph of revisions which represents the history of the project.
Tip
If you want to change a commit deeper in the history (assuming that it was not published, or, at least, there isn’t anyone who based their work on the old version of the said commit), you need to use interactive rebase, or some specialized tool such as StGit (a patch stack management interface on top of Git). Refer to Chapter 10, Keeping History Clean, for more information.

Figure 2.4 – The graph of revisions before and after amending the last commit
If you just want to correct the commit message, assuming you don’t have any staged changes, you simply run git commit --amend and fix it (note that we use git commit without the -a / -- all flag):
$ git commit --amendIf you want to add some more changes to that last commit, you can simply stage them as normal with git add and then amend the last commit, as shown in the preceding example, or make the changes and then use git commit - a --amend:
Important note
There is a very important caveat: you should never amend a commit that has already been published! This is because amending effectively produces a completely new commit object that replaces the old one, as can be seen in Figure 2*.4*. In this figure, you can see that the most recent commit before the operation, denoted by C5, is replaced in the project history by the commit C5’, with amended changes.
If you’re the only person who had this commit, doing this is safe. However, after publishing the original commit to a remote repository, other people might already have based their new work on that version of the commit. In this case, replacing the original with an amended version will cause problems downstream. You will find out more about this issue in Chapter 10, Keeping History Clean.
That is why, if you try to push (publish) a branch with the published commit amended, Git prevents overwriting the published history and asks you to force push if you really want to replace the old version (unless you configure it to force push by default). More about that in Chapter 6, Collaborative Development with Git.
The old version of the commit before amending would be available in the branch reflog and in the HEAD reflog; for example, just after amending, the amended version would be available as @{1}. This means that you can undo the amend operation with, for example, git reset --keep HEAD@{1}, as described in the Rewinding or resetting a branch section. Git would keep the old version for a month (30 days) by default if not configured otherwise, unless the reflog is manually purged.
You can always check the log of operations in the reflog by using the git reflog command. Just after amending a commit, that command output would look like the following:
$ git reflog --no-decorate94d3e03 HEAD@{0}: commit (amend): After amendingd69a0a9 HEAD@{1}: commit: Before amendingHere, HEAD@{1} means the position of the current branch 1 operation back. Besides the HEAD reflog, there is also a reflog for each branch, as described later. Note that you can read more about using reflog to refer to commits in Chapter 4, Exploring Project History.
Working with branches and tags
Section titled “Working with branches and tags”In version control, branches are separate lines of development, a way of separating different ideas and different parts of changes. You can use branches in different ways, which are described in Chapter 8, Advanced Branching Techniques.
Tags are a way to give a meaningful name to mark a specific version of a project. They are used to make it possible to return to a given point in history — for example, with the v1.0 tag, you will be able to go to exactly version 1.0 of the code. Additionally, with annotated tags, you can give a longer description of the tagged revision, and signed tags also help ensure that it was you who created it.
In Git, each branch is realized as a named “ pointer ” (reference) to some commit in the graph of revisions, the so-called branch head. The same is true for lightweight tags; for annotated and signed tags, the “ pointer ” refers to the tag object (with annotation or signature), which points to a commit.
Representation of branches in Git
Git currently uses two different on-disk representations of branches: the “ loose ” format (which takes precedence) and the “ packed ” format.
Take, for example, the master branch (which is currently the default name of the branch in Git; you start on this branch in a newly created repository, unless configured otherwise). In the “ loose ” format (which takes precedence), the branch is represented as the one-line .git/refs/heads/master file with a textual hexadecimal representation of SHA-1 at the tip of the branch. In the “ packed ” format, a branch is represented as a line in the.git/packed-refs file, connecting the SHA-1 identifier of the top commit with the fully qualified branch name.
The (named) line of development is then a set of all the revisions that are reachable from the branch head. It is not necessarily a straight line of revisions — it can fork and join.
Creating a new branch
Section titled “Creating a new branch”When creating a new branch, you can just create it and switch to it later, or you can create it and switch to it with a single command. This is explained in Figure 2*.5*.
You can create a new branch with the git branch command. For example, to create a new testing branch starting from the current branch (see the top-right part of Figure 2*.5*), run the following:
$ git branch testingWhat happens here? Well, this command creates a new pointer (a new reference) for you to move around. You can give an optional parameter to this command if you want to create the new branch pointing to some other commit, like in the following example:
$ git branch testing HEAD^^^
Figure 2.5 – Creating a new branch named “testing” and switching to this branch, or creating a new branch and switching to it at once, with one command
Note
The HEAD^^^ notation will be explained in Chapter 4, Exploring Project History.
However, the git branch <new branch> command would not change which branch is the current branch; it does not switch to the just-created branch. It would not change the position of the HEAD (the symbolic reference pointing to the current branch) and would not change the contents of the working directory.
If you want to create a new branch and switch to it (to start working on a new branch immediately), you can use the following shortcut:
$ git switch -c testingHere, the short -c option stands for --create. You can also use the following alternative command, which is the only option for older Git:
$ git checkout -b testingIf you want to forcibly create a branch with a name that already exists, effectively deleting the existing branch, you will need to use the -C and -B options instead of the -c and -b options, respectively.
If we create a new branch at the current state of the repository, the switch -c and checkout -b commands differ only in that they also move the HEAD pointer; see the transition from the left-hand side to the bottom right in Figure 2*.5*.
Creating orphan branches
Section titled “Creating orphan branches”Rarely, you might want to create a new unconnected orphan branch in your repository that doesn’t share any history with other branches. Perhaps you want to store the generated documentation for each release to make it easy for users to get readable documentation (for example, as man pages or HTML help) without requiring the installation of conversion tools or renderers (for example, AsciiDoc or a Markdown parser). Or, you might want to store web pages for a project in the same repository as the project itself; that is what GitHub project pages can use. Perhaps you want to open source your code, but you need to clean up the code first (for example, because of copyrights and licensing).
One solution is to create a separate repository for the contents of an orphan branch and fetch from it into some remote-tracking branch. You can then create a local branch based on it. This has the advantage of having unconnected contents separately, but on the other hand, it is one more repository to manage.
You can also do this with either the git switch or git checkout command by using the -- orphan option:
$ git switch --orphan gh-pagesSwitched to a new branch 'gh-pages'This reproduces the state similar to just after git init: the HEAD symref points to the gh-pages branch, which does not exist yet; it will be created on the first commit.
If you want to start with a clean state, such as with GitHub Pages, you will also need to remove the contents of the start point of the branch (which defaults to HEAD — that is, to the current branch and the current state of the working directory) — for example, with the following:
$ git rm -rf .In the case of open sourcing code with proprietary parts to be excluded, where the orphan branch is used to make sure not to bring the proprietary code accidentally to the open source version on merging, you would want to carefully edit the working directory instead.
Selecting and switching to a branch
Section titled “Selecting and switching to a branch”To switch to an existing local branch, you need to run the git switch command. For example, after creating the testing branch, you can switch to it with the following command:
$ git switch testingThis is shown in Figure 2*.6* as the vertical transition from the top-right to the bottom-right state; this figure also shows that you can use git checkout to switch branches.
Obstacles to switching to a branch
Section titled “Obstacles to switching to a branch”When switching to a branch, Git also checks out its contents in the working directory. What happens then if you have uncommitted changes (that are not considered by Git to be on any branch)?
Tip
It is a good practice to switch branches in a clean state, stashing away changes or creating a commit if necessary. Checking out a branch with uncommitted changes is useful only in a few rare cases, some of which are described in the following section.
If the difference between the current branch and the branch you want to switch to does not touch the changed files, the uncommitted changes are moved to the new branch. This is very useful if you started working on something and only later realized that it would be better to do this work in a separate feature branch.
If uncommitted changes conflict with changes on the given branch, Git will refuse to switch to the said branch to prevent you from losing your work:
$ git checkout other-brancherror: Your local changes to the following files would be overwritten by checkout: file-with-local-changesPlease commit your changes or stash them before you switch branches.AbortingIn such a situation, you have a few possible different solutions:
- You can stash away your changes with the
git stashcommand and restore them when you come back to the branch you were on. This is usually the preferred solution. Alternatively, you can simply create a temporary commit of the work in progress with those changes, and then either amend the commit or rewind the branch when you get back to it. - You can try to move your changes to the new branch by merging, either with
git switch --merge(which would do the three-way merge between the current branch, the contents of your working directory with unsaved changes, and the new branch), or by stashing away your changes before checkout and then unstashing them after a switch. - You can also throw away your changes with
git switch --discard-changesorgitcheckout --force.
Anonymous branches
Section titled “Anonymous branches”What happens if you try to check out (switch to) something that is not a local branch — for example, an arbitrary revision (such as HEAD^), a tag (such as v0.9), or a remote-tracking branch (for example, origin/master)? Git assumes that you need to be able to create commits on top of the current state of the working directory.
Older Git refused to switch to a non-branch. Nowadays, Git will create an anonymous branch by detaching the HEAD pointer and making it refer directly to a commit (that’s why it is also called a detached HEAD state) rather than being a symbolic reference to a branch; see Figure 2*.6* for an example.

Figure 2.6 – The result of checking out a non-branch is a detached HEAD state (which is like being on the anonymous branch)
Because this feature is used only rarely, to avoid landing in such a state explicitly, the git switch command requires the use of the --detach option; for backward compatibility, git checkout does not require using this option to detach the HEAD pointer. This option is also useful to explicitly create an anonymous branch at the current position. The detached HEAD state is shown in the branch listing as (no branch) in older versions of Git, or (detached from HEAD) or (HEAD detached at…) in newer versions.
If you did detach HEAD by mistake, you can always go back to the previous branch with the following command (where - means the name of the previous branch):
$ git switch -Previous HEAD position was a3bl9 <Some commit message>Switched to branch 'master'Important note
The git switch - command uses the HEAD reflog to switch to a previous branch. This may not work correctly after renaming the branch.
As Git informs you, when creating a detached branch without using the --detach option, you can always give a name to the anonymous branch with git switch - c <new-branch-name>.
Because tags are meant to be immutable, trying to check one out (or switch to it) also creates a detached HEAD — tags are not branches.
The switch command DWIM-mery
Section titled “The switch command DWIM-mery”There is a special case of checking out something that is not a branch. If you check out a remote-tracking branch (for example, origin/next) by its short name (in this case, next) as if it were a local branch, Git would assume that you meant to create new contents on top of the remote-tracking branch state and will do what it thinks you need. This do what I mean (DWIM) feature will create a new local branch, tracking the remote-tracking branch. This behavior can be turned off with the --no-guess option, or the accompanying checkout.guess configuration variable.
This means that:
$ git switch nextis equivalent to:
$ git switch -c next --track origin/nextGit will do it only if there are no ambiguities; the local branch must not exist (otherwise the command would simply switch to the local branch given) and there can be only one remote-tracking branch that matches. The latter condition can be checked by running git show-ref next (using the short name) and verifying that it returns only one line, with remote-tracking branch information:
$ git show-ref --abbrev next4936735 refs/remotes/origin/nextListing branches and tags
Section titled “Listing branches and tags”If you use the git branch command without any other arguments, it will list all the branches, marking the current branch with an asterisk — that is, *.
Programmatically determining the current branch
The git branch command is intended for the end user; its output may change in the future version of Git. To find out programmatically, in a shell script, the name of the current branch, uses git symbolic-ref HEAD (or git branch --show-current). To find the SHA-1 function of the current commit, use git rev-parse HEAD. To list all the branches, use git show-ref or git for-each-ref; this also works for tags and remote-tracking branches.
The git symbolic-ref, git rev-parse, git show-ref, and git for-each-ref commands are all plumbing — that is, commands intended for use in scripts.
You can request more information with -v ( --verbose) or -vv. You can also limit branches shown to only those matching the given shell wildcard with git branch --list <pattern> (quoting the pattern to prevent its expansion by the shell, if necessary).
Querying information about remotes, which includes the list of remote branches, by using git remote show is described in Chapter 8, Advanced Branching Techniques.
To list all tags, you can use the git tag command without any arguments, or git tag --list; with git tag --list <pattern>, you can select which tags to show (such as for branches), as in the following example:
$ git tag --list "v0.9*"v0.99v0.99.1v0.99.2Rewinding or resetting a branch
Section titled “Rewinding or resetting a branch”What do you do if you want to abandon the last commit and rewind (reset) the current branch to its previous position? For this, you need to use the reset command. It would change where the current branch points to. Note that, unlike the checkout command, the reset command does not change the working directory by default; you need to use git reset --keep (to try to keep the uncommitted changes) or git reset --hard (to drop them). The result of such reset operation is shown in Figure 2*.7*.

Figure 2.7 – Rewinding a branch one commit back, to HEAD^, with the reset command
The reset command and its effects on the working area will be explained in more detail in Chapter 3, Managing Your Worktrees.
Note
The git reset <commit> command always changes where the current branch points to (moves the ref), while git switch always modifies where the HEAD points to, either changing the current branch or detaching it.
Deleting a branch
Section titled “Deleting a branch”Because in Git, a branch is just a pointer and an external reference to the node in the DAG of revisions, deleting a branch is just deleting a pointer. This means that deleting the branch does not immediately delete the history, but it might make it not accessible except via reflog. It is not kept forever, though; the garbage collection process would remove unreferenced parts of the commit-graph file after the reflog entries expire.
Important note
Actually, deleting a branch also removes, irretrievably (at least, in the current Git version), the reflog for the branch being deleted — that is, the log of its history of local operations.

Figure 2.8 – Deleting the ‘based-doc’ branch that just got merged into ‘master’, while being on the ‘master’ branch that includes it
You can delete a branch with git branch --delete <branch-name>, or with branch -d, provided that the branch is not checked out anywhere.
There is, however, one issue to consider — what happens if you delete a branch, and there is no other reference to the part of the project history it pointed to? Those revisions will become unreachable, and Git would delete them after the HEAD reflog expires (which, with default configuration, is after 30 days).
That is why Git would allow you to delete only the completely merged-in branch, whose commits are all reachable from HEAD, as in the example in Figure 2*.8* (or if the branch deleted is reachable from its upstream branch, if it exists).
To delete a branch that was not merged in, which risks parts of the DAG becoming unreachable, as seen in Figure 2*.9*, you need a stronger command — namely, git branch -D or git branch --delete --force. Git will suggest this operation when refusing to delete an unmerged branch.

Figure 2.9 – Deleting the unmerged branch, which results in parts of the history being unreachable
You can check whether the branch was merged into any other branch by checking whether git branch --contains <branch> shows anything. You cannot delete the current branch.
If you ever switched to the branch that got deleted, this event and the switch away from the branch will be kept in the reflog for HEAD. This information can then be used to undelete that branch, or rather, to recreate it:
$ git reflog --no-decorate HEAD…3a59408 HEAD@{3}: checkout: moving from base-doc to masterChanging the branch name
Section titled “Changing the branch name”Sometimes, the name chosen for a branch needs to be changed. This can happen, for example, if the scope of the branch changes during the development and the old name no longer fits it. Names of branches will appear and be kept forever, by default, in commit messages for merge commits; that’s why you want them to be meaningful.
You can rename a branch with git branch -m (use -M if the target name exists and you want to overwrite it); it will rename a branch and move the corresponding reflog. This will also change the name of the branch in all of its configuration (its description, its upstream, and so on).
The renaming event is stored in the reflog, where you can find the previous name and use it to undo the operation (to rename the branch back to the old name):
$ git reflog --no-decorate new-name3a59408 new-name@{0}: branch: renamed refs/heads/old-name to refs/heads/new-nameSummary
Section titled “Summary”In this chapter, we have learned how to develop with Git and extend the project history by creating new commits and new lines of development (branches). We know what it means to create a commit, amend a commit, create a branch, switch a branch, rewind a branch, and delete a branch from the point of view of the graph of revisions.
This chapter showed a very important Git feature — the staging area for creating commits, also known as the index. This is what makes it possible to untangle the changes to the working directory by selectively and interactively choosing what to commit.
We learned how to examine the changes to the working area before creating a commit. This chapter described, in detail, the extended unified diff format that Git uses to describe the changes.
We also learned about the concept of detached HEAD (or anonymous branch) and orphan branches.
In Chapter 3, Managing Your Worktrees, we will learn how to use Git to prepare new commits and how to configure it to make our work easier. We will also learn how to examine, search, and study the contents of the working directory, the staging area, and the project history. We will also see how to use Git to deal with interruptions and recover from mistakes.
Questions
Section titled “Questions”Answer the following questions to test your knowledge of this chapter:
- How does creating a new commit change the history stored in the repository — that is, how does it change the graph of revisions and where branch heads point to?
- What is the difference between
git commitandgit commit --all(orgitcommit -a)? - How do you check what changes you have made in the local repository? How do you undo them?
- What is the simplest way to fix an error in the commit message of the last commit on the current branch?
- What do you do when you realize that the changes you started to write (but didn’t commit) should be made on a separate new branch?
- What is the simplest way to switch to the previous branch, and when can it fail?
Answers
Section titled “Answers”Here are the answers to the questions given above:
- Creating a new commit makes a new node in the graph of revisions that has a previous commit as a parent, advances the branch head ref for the current branch to the freshly created node, and keeps
HEADunchanged. - The
git commitoperation creates the new commit out of the staging area contents, while thegit commit --allcreates it out of the changes to all tracked files. - You can use
git statusto examine what files have changed andgit difforgit diff HEADto examine the changes. You can find the explanation of how to undo changes you have made in the fullgitstatusoutput. - To change the commit message (that is, the description of the changes) of the last commit, you can use
gitcommit --amend. - Because uncommitted changes do not belong to a branch, you can simply create a new branch and switch to it with
git switch -c <branch-name>orgit checkout -b <branch-name>. - To switch to the previous branch, you can use
git switch -(with-in place of the branch name). Git finds what the previous branch was by searching reflogs. This operation can fail if the branch was deleted or rename
Further reading
Section titled “Further reading”To learn more about the topics that were covered in this chapter, take a look at the following resources:
- Scott Chacon, Ben Straub. Pro Git, 2nd Edition (2014), Apress, Chapter 2*.2*, Git Basics - Recording Changes to the Repository: https://git-scm.com/book/en/v2/Git-Basics-Recording-Changes-to-the-Repository
- Jakub Narębski. How to read the output from git diff? (the answer to the question on StackOverflow): https://stackoverflow.com/questions/2529441/how-to-read-the-output-from-git-diff/2530012#2530012
- Dragos Barosan. New in Git: switch and restore (2021): https://www.banterly.net/2021/07/31/new-in-git-switch-and-restore/
- Junio C Hamano. Fun with a new feature in recent Git (2016), about the
--sortoption of thegit branchcommand: https://git-blame.blogspot.com/2016/05/fun-with-new-feature-in-recent-git.html - Tobias Günther. A look under the hood: how branches work in Git (2021): https://stackoverflow.blog/2021/04/05/a-look-under-the-hood-how-branches-work-in-git/
- Ryan Tomayko. The Thing About Git (2008), about the tangled working copy problem, and how to resolve it in Git: https://tomayko.com/blog/2008/the-thing-about-git
- Nick Quaranto. Reflog, your safety net (2009), on Gitready: http://gitready.com/intermediate/2009/02/09/reflog-your-safety-net.html