Bookmarks
ReferenceDevOps & cloudBackendVerified

Git

Git is a distributed version control system for code history and collaboration. In this reference: commits, branches, merge, rebase, remote and undoing changes.

checked 6 Nov · next check 13 Nov · 74 min read

Sections
14
Reading
74 min
Current version
2.56.0
Written from
git-scm.com/doc

Check status of the reference

Verified 6 Nov · next check 13 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What Git is and how it is organised

Git is a distributed version control system: it stores the history of project changes as commits. Every developer has a full copy of the repository with all of its history: the history lives on their computer, not only on a server. A commit is a snapshot of the project’s content, not a diff against the previous version.

Files pass through three places on your computer. The working tree is an ordinary directory with the files you edit. The index is an intermediate list of what will go into the next commit. The repository is the hidden .git directory: the project’s entire history is stored in it. git add moves the selected files from the working tree to the index, git commit records the content of the index in the repository as a new commit. The fourth place is outside the computer: the remote. git push sends commits there, git fetch and git pull bring other people’s commits from there; git restore returns to the working tree what is in the index.

Dashed lines — movements in the reverse direction: from the server to you and from the index to the working tree.
bashfirst commit; the default branch is `master`
git initgit add .git statusgit commit

Objects and hashes

The history is an object database inside .git. A commit is a snapshot of the project’s entire content, not a diff against the previous version: an unchanged file goes into the next commit as the same object. Each object is named after the hash of its content — 40 hexadecimal characters (64 in SHA-256 repositories); the first few are usually enough to name an object unambiguously. Identical content produces the same hash in any repository, so an object cannot be changed without changing its name.

  • blob — the content of a single file, without a name or permissions;
  • tree — a directory: a list of names and permissions with links to blobs and nested trees;
  • commit — a snapshot of the project: a link to a tree, the author, the date, the message and a link to the parent commit;
  • tag — a mark on an object, usually a commit: it marks a release; unlike a branch, it does not move as new commits are added.

Branches and HEAD

A branch is a line of development; technically it is a head — a pointer to the branch’s latest commit, which moves forward with each new commit. A repository keeps any number of branches, and the working tree is tied to one of them, the current one; HEAD points to it: the .git/HEAD file holds the name of the current branch. If you switch to an individual commit, you get a detached HEAD: the commits you make belong to no branch. For creating and switching branches, see the section “Branches and HEAD”.

When Git is needed

Git is built for text: source code, configuration files, Markdown documents. Line by line, it shows diffs and finds who changed what. Large binary files are its weak spot: there are no line diffs, compression works worse, the repository grows and cloning slows down.

FilesHow Git handles them
Code, configuration files, Markdownline-by-line diffs, compact history
A few images and PDFsno line diffs, whole versions are stored; acceptable
Video, databases, buildsthe history bloats; keep them outside the repository

What you need to know first

  • Command line: commands, arguments, environment variables — the Bash reference.
  • Files, directories and paths — the Linux reference, the section “File system and paths”.
  • Installing Git and setting up your name and email for signing commits — see the section “Installation and first run”.

Section sources

the section is written from these pages

Cheat sheet

Everyday Git commands: setup, commits, branches, merge and rebase, remotes, history and undo. Replace the names in the examples (feature/login, app.py, origin) with your own. Details and pitfalls are covered in the main sections of the reference.

Setup

TaskCommand
Author name for commitsgit config --global user.name "Anna Ivanova"
Author email for commitsgit config --global user.email anna@example.com
Name of the first branch in new repositoriesgit config --global init.defaultBranch main
Where each setting comes fromgit config --list --show-origin
Create a repository in the current directorygit init

Commits

TaskCommand
What has changed since the last commitgit status
Changes not yet in the indexgit diff
Add a file to the indexgit add app.py
Select individual hunks within a filegit add -p
Commit with a message, git commit -mgit commit -m "Fix login redirect"
Commit changes in all tracked filesgit commit -a -m "Add password reset"
Add changes to the last commitgit commit --amend

Branches

TaskCommand
List branchesgit branch
Switch to a branchgit switch main
Create a branch and switch to itgit switch -c feature/login
Delete a merged branchgit branch -d feature/login
Tag a commitgit tag v1.0
Tag with a messagegit tag -a v1.0 -m "Release 1.0"

Merge and rebase

TaskCommand
Merge a branch into the current one, git mergegit merge feature/login
Abort a merge in progressgit merge --abort
Move the branch’s commits onto maingit rebase main
Continue a rebase after a conflictgit rebase --continue
Abort a rebase in progressgit rebase --abort
Pick a commit from another branchgit cherry-pick 4f2e1a9

Remote repositories

TaskCommand
Clone a repositorygit clone https://example.com/team/app.git
Add a second remotegit remote add upstream https://example.com/org/app.git
Fetch branches without merginggit fetch origin
Remove entries for branches deleted on the servergit fetch --prune
Fetch and merge in one stepgit pull
Push commitsgit push
First push of a new branchgit push -u origin feature/login
Delete a branch on the servergit push -d origin feature/login

History

TaskCommand
Recent commits, one line eachgit log --oneline -5
History with a branch graphgit log --oneline --graph
History of all branches, including remotesgit log --oneline --graph --all
History of a single filegit log -- app.py
Commits on a branch that are not in maingit log main..feature/login
A full commit: message and changesgit show 4f2e1a9
Who changed each line of a file and whengit blame app.py

Undo

TaskCommand
Discard changes to a file in the working treegit restore app.py
Unstage a file, keep the changesgit restore --staged app.py
Set changes asidegit stash
Bring stashed changes backgit stash pop
Undo the last commit, keep changes in the indexgit reset --soft HEAD^
Undo a commit with a new commitgit revert 4f2e1a9
Where branches and HEAD pointed earliergit reflog
Discard all changes in the working treegit reset --hard
Remove files that Git does not trackgit clean -fd
Push a branch after history has been rewrittengit push --force-with-lease

Section sources

the section is written from these pages

Installation and first run

Git is installed from distribution packages or the official installer; after that, before the first commit, you set your name, email and the default branch name. The installation is checked with git --version, the configuration with git config --list --show-origin.

Linux

On Ubuntu and Debian the package is installed with apt, on RHEL, Fedora and CentOS Stream — with dnf. You use sudo for root privileges; Git needs no separate group:

bashUbuntu and Debian
sudo apt updatesudo apt install git
bashRHEL and Fedora
sudo dnf install git

On macOS Git comes with the Xcode Command Line Tools and appears after you type git --version in the terminal; a fresh version is installed and updated with Homebrew (brew install git). On Windows Git is installed by the Git for Windows installer or by the command winget install --id Git.Git -e --source winget — the Git for Windows project maintains both.

bashon the host
git --version
textexample output
git version 2.56.0

First settings

Your name and email go into the author and committer fields of every commit you make:

bashon the host
git config --global user.name "Anna Ivanova"git config --global user.email "anna@example.com"

Git 3.0 will make the main branch the standard, but for now the initial branch without configuration is called master. init.defaultBranch or the git init -b flag sets the name of the first commit’s branch:

bashon the host
git config --global init.defaultBranch main

Git chooses the editor for commit messages and interactive rebase in this order: GIT_EDITOR, then core.editor, then $VISUAL and $EDITOR, then the editor selected at build time, usually vi. On a server without EDITOR this may turn out to be vi — set the editor you are used to:

bashon the host
git config --global core.editor nano

The git pull command fetches other people’s commits (git fetch) and integrates them into the current branch. If the histories have diverged, without configuration Git stops the pull and asks you to choose how to integrate them. The value true makes rebase the default: local commits are replayed on top of the fresh commits, as with git pull --rebase. The value false chooses a merge: when the histories have diverged, a merge commit appears; the other values of the setting are described in the section “Rebasing and rewriting history”.

bashon the host
git config --global pull.rebase true

Settings levels

Settings are stored on several levels. Without a flag git config writes to the local level; the --global and --system flags choose another one. When reading, a lower-level value overrides the one above, so keep your personal email in --global and the corporate one in the --local settings of your work repository:

LevelFileWho it covers
--system/etc/gitconfigall users of the machine
--global~/.gitconfig or ~/.config/git/configyou in all repositories
--local.git/config in the repositoryonly this repository

Where a setting came from

bashon the host
git config --list --show-origin --show-scope
textexample output
system  file:/etc/gitconfig  init.defaultbranch=masterglobal  file:/home/anna/.gitconfig  init.defaultbranch=mainlocal   file:/home/anna/demo/.git/config  user.email=anna@corp.example.com

--show-origin prints the file of each setting, --show-scope — its level: system, global, local or worktree. The list shows all the values that are set, and the lower level is the one that takes effect: here init.defaultBranch will be taken from ~/.gitconfig, not from /etc/gitconfig. A single key is shown like this: git config user.email.

First repository

git init turns the current directory into a repository: it creates the .git subdirectory with the object store and an empty initial branch. The -b main flag sets the initial branch’s name, bypassing init.defaultBranch; after that, all that is left is to make the first commit — see the section “Commits and the index”:

bashon the host
mkdir demo && cd demogit init -b main

git clone downloads a ready-made repository in full: it sets up the remote origin and creates remote-tracking branches for its branches, for example origin/main. You take the HTTPS address from the repository’s page; other protocols work too, for example SSH (the second line):

bashon the host
git clone https://example.com/team/app.gitgit clone ssh://git@example.com/team/app.git

Section sources

the section is written from these pages

Commits and the index

A commit is a snapshot of the project recorded in the repository: it stores the content of all files, the author, the date, the message and a link to the parent — the previous commit. The next commit is assembled in the index (the staging area) with git add and recorded with git commit.

The link to the parent ties a commit to the history of its branch; the very first commit has no parent. The author’s name and email come from the user.name and user.email settings. Every commit gets a hash by which it is found in the history — see the section “Viewing the history” for how.

git commit without arguments records in the commit only what is in the index at that moment. What has not been added stays in the working tree and waits for the next commit. This is how a large piece of work is split into several commits: a fix on its own, a new feature on its own, a reformatting on its own.

git commit records in the repository what is in the index at that moment.

What git status shows

git status lists files in three groups: Changes to be committed — the index, ready for the commit; Changes not staged for commit — changed in the working tree but not yet added; Untracked files — new files that Git does not track yet. Git shows command hints right there in the output: git restore --staged removes a file from the index, git add adds it.

bashin the project directory
git statusgit add app.pygit diff --stagedgit commit
textexample output
On branch mainChanges to be committed:  modified:   app.pyChanges not staged for commit:  modified:   main.pyUntracked files:  notes.txt
StateWhere the file isWhat to do
Untrackedonly in the working tree, Git does not track it yetgit add
Modifiedhas changed in the working tree since the last commitgit add — it will go into the next commit
In the indexadded with git add, ready for the commitgit commit or git restore --staged
Unchangedmatches the last commitnothing is needed
Ignoredlisted in .gitignore, hidden from git statusgit add -f, if you do need it

What to put in .gitignore

Files that Git should not track are listed in .gitignore at the root of the repository: build artefacts, dependencies, local settings and secrets, editor and operating system service files. Ignored files are not shown in git status and are not added by git add .; a single file can still be added deliberately with git add -f.

bash.gitignore at the root of the project
# build artefacts and dependenciesbuild/node_modules/# local settings and secrets.env# editor service files and logs.idea/*.log

The rules apply to the directory containing the .gitignore file and below; there can be several such files. Commit the .gitignore itself — then the rules reach everyone who clones the repository. Personal exceptions that you do not want to share go into .git/info/exclude.

Committing part of a file

git add -p shows changes hunk by hunk and asks for a decision on each one — you can review the difference before adding it. The main answers:

  • y — add the hunk to the index;
  • n — skip the hunk;
  • a — add this and all remaining hunks of the file;
  • d — skip to the end of the file;
  • q — quit without processing the rest.

Before committing, review the changes: git diff shows what has changed in the working tree and has not yet gone into the index; git diff --staged — what is already staged for the next commit. The two flags are equivalent; the historical name of the second is --cached.

The commit message

Git treats the text before the first blank line as the commit subject: it is what you see in git log --oneline and in the commit lists of graphical interfaces. The recommended shape is a subject of up to 50 characters that says what has changed, then a blank line, then a body with details and reasons if they are needed. The -m flag sets a short message; several -m flags give several paragraphs.

texta commit message
Fix token refresh on expired session Refresh used the access token instead of therefresh token, so users logged out every hour.
bashin the project directory
git commit -m "Add retry to sync" \  -m "Retries stop after five attempts"

Amend the last commit

git commit --amend replaces the tip of the branch, the last commit, with a new one: with the same parent and author but with the content of the current index. The previous message opens in an editor for editing; the --no-edit flag leaves it as it is. --amend is handy when you forgot a file, spotted a typo in the message, or want to add the last touches.

bashin the project directory
# add the forgotten file to the last commitgit add notes.mdgit commit --amend --no-edit

How many commits to make and how to group them is decided by the branching model — see the section “Branching models”. Undoing a commit without rewriting history — the section “Undoing changes”.

Section sources

the section is written from these pages

Branches and HEAD

A branch is a moving pointer to a commit: a name attached to the latest commit of a line of development. Creating a branch does not copy files — Git merely registers a new name, so the branch appears instantly. HEAD shows where the working tree currently is — a pointer to the current branch.

On disk, a branch is a record with the hash of the commit it points to: a separate file in .git/refs/heads or a line in .git/packed-refs, where Git stores references during garbage collection. HEAD is the file .git/HEAD; it usually holds the name of the current branch. Every commit refers to its parent — the previous commit of the same line — so a single name determines the whole chain of history back to the root. A new commit moves the branch: the tip of a branch always shows its latest commit.

Creating a branch does not switch you to it on its own: the working tree stays on the previous branch until you run git switch.

The arrow from a commit leads to its parent.

Create a branch and switch to it

bashin the project directory
git switch -c feature/login# work and commit in the new branchgit switch maingit switch -

git switch -c creates a branch from the current commit and switches to it right away — it replaces the pair of git branch and git switch. The starting point can be another commit or branch: git switch -c fix/docs origin/main. If the name exists only in the remote, git switch fix/docs will itself create a local branch that tracks it.

TaskCommand
List local branches — the current one is marked with an asteriskgit branch
List branches together with remote-tracking branchesgit branch -a
Only the name of the current branchgit branch --show-current
Create a branch without switching to itgit branch fix/header-order
Create a branch and switch to itgit switch -c feature/login
Create a branch from a given commitgit switch -c fix/docs 4f2e1a9
Switch to a branchgit switch main
Return to the previous branchgit switch -
Rename a branchgit branch -m feature/login feature/auth
Delete a merged branchgit branch -d fix/header-order
Force-delete a branchgit branch -D fix/header-order

Delete and rename

bashin the project directory
# the merge has already been madegit branch -d fix/header-order# the branch is not merged and the work is not neededgit branch -D fix/header-order

HEAD and detached HEAD

HEAD usually names a branch, and then every new commit moves that branch. If you switch to an individual commit, HEAD will remember the hash instead of the branch name — this state is called a detached HEAD. It is used to look at old code and try out ideas: git switch --detach HEAD~3 puts the working tree on the commit three steps before the tip of the branch.

bashin the project directory
# look at the code at a commit without a branchgit switch --detach HEAD~3# the commit turned out to be useful — pin it with a branchgit switch -c good-surprises

In a detached HEAD, commits are recorded, but no branch points to them. If you switch to a branch at that moment, the new commits will be left without names, and Git will eventually delete them during garbage collection. Save your work without leaving the commits: git switch -c good-surprises will create a branch right here. If you have already left, the hash can be recovered from the HEAD movement log, git reflog, and git branch good-surprises 4f2e1a9 will create a branch on the commit you find.

switch and restore instead of checkout

In the past, both actions were performed by a single command, git checkout: without a path it switched branches, with a path it reverted files. Now each task has its own command: git switch changes the branch and the position of HEAD, git restore restores files in the working tree and the index. git checkout still works and understands both actions.

Actionswitch and restorecheckout
Switch branchesgit switch maingit checkout main
Create a branch and switch to itgit switch -c feature/logingit checkout -b feature/login
View an individual commitgit switch --detach HEAD~3git checkout HEAD~3
Revert edits in a filegit restore app.pygit checkout -- app.py

Branch names

Branches, tags and remote-tracking branches are references in the shared refs namespace: main is a short name for refs/heads/main, the tag v1.2.0 for refs/tags/v1.2.0 and origin/main for refs/remotes/origin/main. The naming rules are the same for all of them, and in repositories names are often written with a task prefix separated by a slash: feature/login, fix/header-order, release/1.2.

  • the name contains no spaces, ~, ^, :, ?, *, [ or \;
  • contains no .. or @{ and is not a single @;
  • does not start with a dot or a slash and does not end with a dot, .lock or a slash;
  • a branch name, on top of the general rules, does not start with a hyphen;
  • does not contain two slashes in a row;
  • if a tag and a branch share a name, the short name means the tag, so the branch is written with its full name: refs/heads/main.

The name of the first branch in a new repository is set by the init.defaultBranch setting; without it Git will name the branch master, and from Git 3.0 it will name it main. For how to change the setting, see the section “Installation and first run”.

Tags: lightweight and annotated

A tag is a fixed name on a commit: a branch moves with every commit, a tag stays in place. A lightweight tag is just a name for an object; an annotated tag, created with the -a flag, is a separate object with a date, an author name, a message and, optionally, a signature. The documentation calls annotated tags release tags and lightweight tags personal, temporary markers; some commands, such as git describe, ignore lightweight tags by default.

bashin the project directory
# annotated tag for a releasegit tag -a v1.2.0 -m "Release 1.2.0"# lightweight tag for a temporary markergit tag v1.2.0-rc1 4f2e1a9git tag --list "v1.2*"git tag -d v1.2.0-rc1

For a branch’s life on the server — remote-tracking branches and git push — see the section “Remotes”; for ready-made branching schemes, see “Branching models”.

Section sources

the section is written from these pages

Merging and conflicts

A merge brings one branch into another: Git joins two lines of development and records the result in the current branch. Usually branches diverge and come back together on their own; if two people have made the same change, Git stops and asks you to resolve the conflict by hand.

git merge <branch> merges the given branch into the current one. First, finish what you are working on: commit your changes or set them aside with git stash. If uncommitted changes touch the same files, Git will refuse to start the merge.

bashin the project directory
git switch maingit merge feature/login

Fast-forward or a merge commit

If the main branch has not moved since the divergence point, there is nothing to merge: simply move the branch pointer to the tip of the incoming branch. This is called a fast-forward: the history stays linear and no merge commit is created. It happens on every git pull when there are no local commits.

On the right, commit M has two parents: the tip of main and the tip of the incoming branch.

When the branches have already diverged, Git combines the changes with a three-way merge and creates a merge commit with two parents: the tip of the current branch and the tip of the incoming branch. A message is usually already prepared for it, and git merge --edit lets you edit it before committing.

FlagWhat it does
--ffdefault: a fast-forward, or a merge commit if the branches have diverged
--no-ffalways a merge commit, even when a fast-forward is possible
--ff-onlya fast-forward only; if the branches have diverged, it fails with an error
--squashthe merge result is placed in the index without a merge commit and without a link to the source branch
--no-commitstop the merge before the merge commit is created
--abortcancel the merge in progress and return to the state before it

The --ff-only flag protects against unexpected merge commits, for example when updating a branch with git pull. --squash gathers the branch’s changes into a single commit but does not record the link to the source: the new commit has a single parent, and git merge will not show that branch as merged later.

bashin the project directory
# fast-forward or fail, no merge commitsgit pull --ff-only# one commit instead of the branch historygit merge --squash feature/logingit commit

Conflict: what happened

If the same line was changed differently in the two branches, the automatic merge stops before the commit is made: “Automatic merge failed; fix conflicts and then commit the result”. The conflicting paths are marked as unmerged in the index, git commit refuses to run until the conflicts are resolved, and the markers are left in the files:

textmarkers in the conflicting file
<<<<<<< HEADVersion from your branch=======Version from the incoming branch>>>>>>> feature/login

Between <<<<<<< HEAD and ======= is the version of the current branch; between ======= and >>>>>>>, the version of the incoming branch. Git has already updated the files that merged cleanly in both the index and the working tree. git status shows the exact list of conflicting paths and a hint (example from Git 2.56):

bashin the project directory
git status
textexample output
On branch mainYou have unmerged paths.  (fix conflicts and run "git commit")  (use "git merge --abort" to abort the merge) Unmerged paths:  (use "git add <file>..." to mark resolution)	both modified:   app.py	both modified:   config.py no changes added to commit (use "git add" and/or "git commit -a")

To find the commit a conflicting change came from, use git log — see the section “Viewing history”.

Resolve the conflict

  1. open the conflicting file and remove the <<<<<<<, ======= and >>>>>>> markers, keeping the version you need or combining both;
  2. check the result: during a merge, git diff shows only the conflicts;
  3. mark the path as resolved: git add app.py — or git add --resolved app.py, which will not let a forgotten marker slip through;
  4. finish the merge: git commit with the prepared message or git merge --continue.
bashin the project directory
# after editing the filegit add --resolved app.pygit merge --continue

The --resolved flag appeared in Git 2.56; in earlier releases a path is marked as resolved with plain git add. Until the path is resolved, the index holds three versions of the file — the merge stages: the version of the common ancestor, the version of HEAD and the version of the incoming branch. They are shown by git ls-files -u and git show :2:app.py, git show :3:app.py. Once the path is marked as resolved, the three versions collapse into one and the file disappears from the unmerged list. The commit message is already filled in with the merge details — you can add your own lines.

mergetool and the conflict style

For complicated conflicts it is handy to open a graphical tool: git mergetool launches an external merge program for each unresolved path. The --tool flag selects the tool, for example meld or vimdiff; by default the merge.tool setting is used, and git mergetool --tool-help lists the available tools.

bashin the project directory
git mergetool --tool=meld# one file at a timegit mergetool --tool=meld app.py

The merge.conflictStyle setting controls how much the markers show. By default the merge style shows only the two versions — as in the example above. The diff3 style adds a third fragment: the original text of the common ancestor between ||||||| and ======= — and you can see what exactly each side changed. The zdiff3 style does the same and also moves the matching lines from the start of the conflicting hunks out of the conflict, so the conflicting hunk is smaller.

bashon your computer
git config --global merge.conflictStyle zdiff3

Undoing a merge after a commit, rolling back a failed git pull and restoring a file to its pre-merge version — see the section “Undoing changes”.

Section sources

the section is written from these pages

Rebasing and rewriting history

Rebase moves a series of commits onto a new base — for example, a fresh commit of main — instead of merging. The commits are recreated with new hashes, and the history of the branch stays linear. Already published commits must not be rewritten: others may have built on them.

Rebase takes the commits of your branch made since it diverged from the base and applies them one by one on top of the new base. The changes are the same, but every commit is recorded anew and gets a new hash. The old commits stay in the object store while a reflog entry points to them and are deleted later by garbage collection.

The hashes of E’ and F’ differ from those of E and F: rebase creates new commits.

Merge or rebase

Both approaches bring the fresh commits of main into your branch. Merge adds a merge commit on top and keeps the old hashes; rebase moves your commits onto the new base and changes them.

AspectMergeRebase
Historya merge commit, branching is visiblelinear, no merge commits
Hashes of your commitsunchangednew for every commit
Conflictsresolved oncerebase stops at every conflicting commit
Published branchsafea forced push is required
When to choose itshared branches, the branching history mattersa personal branch before review

Choose rebase for personal branches: in review, a series of commits reads as a single linear history. Merge is safer for shared branches and when the branch points matter. How a merge proceeds — see the section “Merging and conflicts”.

How to rebase

bashin the working tree
git switch feature# move the feature commits onto a fresh maingit rebase main

Rebase stops at the first commit that cannot be applied without a conflict. Fix the files, add them to the index and continue: there is no need to run git commit — --continue will create the commit itself.

bashafter resolving a conflict
git add .# instead of git commitgit rebase --continue

There are other ways to leave a stopped rebase:

  • git rebase --skip — skip the commit that caused the conflict
  • git rebase --abort — abort the rebase and return the branch to its original state

Interactive rebase

git rebase -i opens an editor with a list of commits from the chosen base to the tip of the branch. The lines can be reordered and deleted: the list is executed from top to bottom, and the order of the lines becomes the order of the commits.

bashthe list of rebase steps
pick a1b2c3d add error handlingreword e4f5a6b refine the commit messagesquash c7d8e9f fixes to error handlingfixup 0f1e2d3 minor correctionsdrop 5a4b3c2 debug output
  • pick — apply the commit as is
  • reword — apply it and edit the message
  • squash — fold into the previous commit, combining both messages
  • fixup — fold into the previous commit, keeping only its message
  • edit — stop after the commit to rework it
  • drop — leave the commit out; deleting a line from the list does the same

It is convenient to prepare corrections to older commits in advance: git commit --fixup a1b2c3d creates a commit with the message “fixup! …”. With the --autosquash flag, the rebase will move it in the list to just after a1b2c3d and mark it as fixup on its own.

bashin the working tree
# a correction to commit a1b2c3dgit commit --fixup a1b2c3d# the list is assembled automatically, confirm and gogit rebase -i --autosquash main

A single commit: cherry-pick

git cherry-pick applies the changes of existing commits to the current branch and records a new commit for each one. This is a targeted transfer: take a fix from another branch without moving the branch in full. The working tree must be clean. On a conflict, cherry-pick stops; after resolving the conflicts run git cherry-pick --continue — the same way as in a rebase.

bashon main
git switch main# take the fix from the hotfix branchgit cherry-pick 4d5e6f7

Published commits

Other copies of the repository refer to published commits by their hashes: a colleague’s origin/main points to a specific commit. After a rebase, new commits stand where the old ones were, and for everyone who has already fetched the history it now diverges from yours — they have to move their own work over by hand.

After a rewrite, a branch is published only with a forced push: a plain Git will not accept it — the new commits do not continue the remote history (non-fast-forward). But git push --force overwrites the branch without any checks at all.

bashafter rewriting a branch
# instead of --forcegit push --force-with-lease

--force-with-lease updates the branch only if the server still has the commit you saw at your last fetch: someone else’s work stays intact. Rewrite only branches where you work alone. The old commits after a failed rebase can be found in the reflog and the branch restored — see the section “Undoing changes”.

Section sources

the section is written from these pages

Remotes

A remote is the version of the project on another computer, usually a server or a hosting service such as [[GitHub]]. Git keeps its address under a short name, most often origin, and exchanges commits with it: git fetch brings in other people’s work, git push sends yours.

The exchange happens in two independent steps. To fetch commits — git fetch; to work them into your branch — git merge or git rebase. git pull does both steps at once: fetch first, then the integration. To send your commits to the server — git push.

A branch on the server cannot be pictured as a single file: it lives in the shared object store together with the commits. So “push a branch” means transferring the commits the server does not have yet and moving the branch name there onto the new commit. Remote-tracking branches such as origin/main are local copies of the server’s names: Git updates them on fetch, and your edits in them are not sent to the server until you push.

The fetch arrow always points towards you, push — away from you.

Connect a repository

After git clone, a remote is already connected under the name origin. For a repository created with git init, connect the server manually — the address comes in two forms: HTTPS asks for a login and a token, SSH works with keys and is convenient for daily work.

bashin the project directory
git remote add origin git@example.com:team/app.gitgit remote -v# origin  git@example.com:team/app.git (fetch)# origin  git@example.com:team/app.git (push)

The git remote commands change only the local configuration and never touch the server itself. git remote -v shows the addresses for fetch and push, set-url changes the address, for example after the project has moved; git remote remove disconnects the repository together with its remote-tracking branches.

TaskCommand
List remotes with their addressesgit remote -v
Connect a remotegit remote add origin git@example.com:team/app.git
Change the addressgit remote set-url origin git@example.com:team/app.git
Disconnect a remotegit remote remove origin
Show the address of one repositorygit remote get-url origin

Fetch commits: fetch

git fetch origin contacts the server, downloads new commits and tags and moves the remote-tracking branches: origin/main, origin/feature/login. Your branches and the files in the directory stay untouched, so fetch is safe at any moment.

bashin the project directory
git fetch origin# compare your branch with the server’sgit log main..origin/main --onelinegit diff main origin/main

Remote-tracking branches are your copy of the server’s state at the moment of the last fetch. The git branch -vv command shows, for each local branch, the remote it is tied to and the divergence: “ahead 2” — two commits are waiting to be sent, “behind 3” — three commits from the server are not worked in yet.

bashexample output
git branch -vv# * main abc1234 [origin/main: ahead 2] message

A branch that exists on the server but not locally appears as origin/feature/login. To start working on it, switch to it: git switch feature/login will create the local branch tied to the remote one by itself. When the branch has been deleted on the server, the local copy origin/… keeps hanging around; to remove such entries — git fetch --prune.

Work the commits in: merge, rebase and pull

After the fetch, choose how to work other people’s commits into your branch. git merge origin/main creates a merge commit and keeps both lines of history, git rebase origin/main reapplies your commits on top of the server’s — for details, see the section “Rebase and rewriting history”.

The git pull command combines the two steps: fetch plus integration. When the branches have diverged, it refuses and asks you to choose how to work other people’s commits in: git pull --rebase reapplies your commits, git pull --no-rebase does a merge; the usual mode is set with the pull.rebase setting. To allow only a fast-forward, use the --ff-only flag.

Send: push

git push transfers to the server the commits it does not have yet and moves the branch name. For the first push of a new branch, add the -u flag: it remembers the “local branch — server branch” pair (the upstream), after which git push and git pull without arguments work with the right branch.

bashin the project directory
# first push of a new branchgit push -u origin feature/login# every push after that is shortergit push

By default, git push sends the current branch to the branch of the same name on the server (the push.default=simple setting); the full address of a branch looks like refs/heads/main. Tags are not part of an ordinary push — they are sent separately with git push --tags, and so is deleting a branch on the server: git push -d origin feature/login.

TaskCommand
Push the current branchgit push
First push with the upstream setgit push -u origin feature/login
Push all local tagsgit push --tags
Push a specific taggit push origin v1.2.0
Delete a branch on the servergit push -d origin feature/login
Delete a tag on the servergit push -d origin v1.2.0

If a push is rejected

The server rejects a push with the non-fast-forward error when the server has commits that you do not: the branch name cannot be moved in a way that would lose somebody else’s work. The standard way out is to fetch and work the commits in: run git fetch, then merge or rebase, and repeat the push. Examine the divergence before pushing again.

bashin the project directory
git fetch origingit rebase origin/main# the push will go through nowgit push

Learn more

The refspec format defines which branches to push and fetch; the --mirror mode of git clone and git remote is suitable for a backup. For setting up SSH keys — see the Linux reference, the section “Access and initial setup”.

  • git push --follow-tags — also push the annotated tags that a push reaches;
  • git remote show origin — a report about the server: HEAD, the branches for push and fetch;
  • git remote set-branches — narrow the list of branches that fetch brings in;
  • git push --atomic — the server applies all the refs or none.

Section sources

the section is written from these pages

Viewing the history

The commit history answers the questions “who, when and why”: git log lists commits with filtering by author, date and content, git blame shows which commit each line of a file came from, and git bisect finds the commit that broke the code.

By default, git log shows the commits reachable from HEAD in reverse chronological order: the hash, the author, the date and the message. Flags change the format and the filtering, and ranges such as main..feature/login restrict the output to a single branch.

bashin the project directory
git log --oneline --graph --all
textexample output
* 4f2e1a9 (HEAD -> main) Add retry to sync* a1b23f4 Fix token refresh on expired session| * c7d9012 (feature/login) Add login rate limit|/* 33ee5c1 (origin/main) Split sync into chunks
FlagWhat it shows
--onelineone line per commit: the short hash and the message subject
--graphthe branch graph on the left: where branches diverge and merge
--allcommits from all branches and tags, not only those reachable from HEAD
-pthe changes of each commit; --stat — file names and line counts only
--author=commits whose author or committer (--committer=) matches the regular expression
--since=2026-10-01commits newer than the date; together with --until= it sets an interval
--grep=commits whose message contains the search string; a regular expression as well
-S "refresh_token"commits where the number of occurrences of the string changes
-Gcommits whose changes contain a string matching the regular expression
-- app/only the commits that changed the path after --
--follow -- app.pythe history of a file across renames; works for a single file

Who changed a line: git blame

git blame app.py prints the file line by line and shows the commit, the author and the date to the left of each line. The hash changes from line to line where different commits made the edits — this is how you find the author of a disputed edit and the reason behind it. The command is about the file’s past; to edit the file itself, see the section “Undoing changes”.

bashin the project directory
git blame -w -L 12,30 app.py

-w ignores changes to whitespace and indentation, and -L 12,30 limits the examination to a range of lines. A mass-reformatting commit gets in the way of blame: it becomes the author of half the lines. The --ignore-rev flag assigns its edits to the neighbouring commits, as if the reformatting had never happened. The list of such commits is kept in the .git-blame-ignore-revs file at the root of the repository and is enabled with the blame.ignoreRevsFile setting — the rule then applies to the whole team.

Commit ranges

A revision is given as a hash or its unique prefix (4f2e1a9), the name of a branch or a tag, or the word HEAD — the current commit. Suffixes count steps along the parents: HEAD~3 is three commits back along the first parent line, HEAD^2 is the second parent of a merge commit. Dot ranges select a group of commits at once.

NotationWhat it means
HEAD~3the third commit back along the first parent line
main..feature/loginthe commits of the branch that are not in main — a merge candidate
..origin/mainwhat has appeared on the server since the histories diverged; the missing end is HEAD
origin/main..your own commits since diverging from the server
main...feature/logincommits reachable from exactly one of the range’s two ends
bashin the project directory
git log main..feature/login --onelinegit log ..origin/main --oneline

What a commit changed: git show and git diff

git show 4f2e1a9 prints the commit in full: the message, the author, the date and the file changes. For a merge commit, git show shows the combined diff — how the result of the merge differs from both parents.

bashin the project directory
git show 4f2e1a9git show 4f2e1a9 -- app.py

In git log and git diff, three dots mean different things. git log A...B selects commits, while git diff A...B compares B with the common ancestor of A and B (the merge base) — what the merge will add to main. Two dots in git diff compare the tips directly: the delta also includes the edits that A has already received by another route.

bashin the project directory
git diff main...feature/logingit diff main feature/login

Find the commit that broke the code: git bisect

When a test fails and dozens of commits are under suspicion, the range is halved: git bisect runs a binary search between the commit where everything worked and the commit where it is already broken. A dozen commits come down to three or four checks.

bashin the project directory
git bisect startgit bisect badgit bisect good v1.4.0

Git checks the middle of the range and prints how many commits are left and how many more checks it expects. Run the tests and mark the commit git bisect good if it works or git bisect bad if it does not — the step repeats until the first bad commit is found. A commit that cannot be built or tested is skipped with git bisect skip. When the commit is found, git bisect reset returns you to the original branch.

bashin the project directory
git bisect start HEAD v1.4.0git bisect run make testgit bisect reset

git bisect run tests automatically: Git runs the command at every step and sets the marks itself. Exit code 0 means the commit is good; an exit code from 1 to 127, except 125, means it is bad; any other code stops the search. Exit code 125 asks to skip a commit that cannot be tested.

What to do with the commit that has been found — undo it or carry its edits over to another branch with a cherry-pick — is described in the sections “Undoing changes” and “Rebase and rewriting history”.

Section sources

the section is written from these pages

Undoing changes

In Git you can undo an edit to a file, a commit, or even a botched rebase: changes rarely disappear for good. Which command to choose depends on whether the commit has been published and what you need to keep; a lost commit is found in the reflog, the log of HEAD movements.

What to undoCommandIs it risky
An edit to a filegit restore file.pyedits to the file are lost
A file in the indexgit restore --staged file.pysafe: the file remains modified
Uncommitted edits, for the time beinggit stash pushsafe
The last commit — keep the editsgit reset --soft HEAD~1safe if the commits are not published
The last commit — discard the editsgit reset --hard HEAD~1loses uncommitted edits
A published commitgit revert HEADsafe: creates a new commit

The three undo commands

Three commands with similar names handle undoing in Git. git restore returns files in the working tree or the index to the chosen state and does not touch history. git reset moves the branch pointer to another commit and, depending on the flags, decides what to do with the index and the working tree. git revert does not delete a commit but adds a new one with the opposite changes.

A commit cannot be ‘deleted’ — you can only move the branch pointer so that the commit becomes unreachable. As long as it is still visible in the reflog, it is not lost; the garbage collector will remove it later.

Undoing edits to files

git restore overwrites files from a source: by default from the index, with --staged from the HEAD commit, and with --source from any commit. The edits are lost in the process.

bashin the repository
# restore a file to the last commitgit restore app.py # remove a file from the index, the edits staygit restore --staged app.py # restore the index and the file at oncegit restore --staged --worktree app.py # take the contents from another commitgit restore --source 1a2b3c4 config.yaml

git reset: three modes

By default git reset (the --mixed mode) moves the branch to the given commit and brings the index in line with it; the files in the working tree stay unchanged. The --soft mode touches neither the index nor the working tree — it suits squashing the last commits into one. The --hard mode brings both the index and the working tree to the commit, and uncommitted edits are lost.

ModeIndexWorking tree
--softunchangedunchanged
--mixed (by default)reset to the commitunchanged
--hardreset to the commitreset to the commit
bashin the repository
# squash the last 3 commits into onegit reset --soft HEAD~3git commit -m "Single edit" # drop the last commit, the edits remaingit reset --mixed HEAD~1 # throw away the commit and all editsgit reset --hard HEAD~1

git revert: undoing a published commit

Once a commit has reached the shared repository, history is not rewritten: colleagues have already built on it. git revert takes the commit, works out the reverse patch and records a new commit — history grows, nothing is lost. A clean working tree is required.

bashin the repository
# undo a single commitgit revert 1a2b3c4 # undo a merge: 1 is the main linegit revert -m 1 9f8e7d6

For a merge, the -m 1 flag sets the number of the parent that is treated as the main line. Without it, git revert refuses to undo a merge commit.

Recovering a lost commit

A commit that git reset --hard or a rebase cut off from the branch is still alive in the repository. The reflog (git reflog) records the position of HEAD after every action:

bashin the repository
git reflog
textexample output
4e5f6a7 (HEAD -> main) HEAD@{0}: rebase (finish): returning to refs/heads/main4e5f6a7 HEAD@{1}: rebase (pick): form edits8b9c0d1 (origin/main) HEAD@{2}: rebase (start): checkout origin/maina1b2c3d HEAD@{3}: commit: form edits...

HEAD@{0} is the current value of HEAD, HEAD@{1} is one step back, main@{one.week.ago} is where the main branch was a week ago. Records for reachable commits are kept for 90 days, for unreachable ones for 30.

bashin the repository
# go back to the commit before the rebase: take the record number from your own refloggit reset --hard HEAD@{3}

Instead of moving the branch, you can carry on working from the lost point: git branch restore-work a1b2c3d creates a branch on the found commit.

Stashing edits: git stash

git stash push puts uncommitted edits into a separate store and returns the working tree to the HEAD commit; git stash pop brings them back. It comes in handy when you need to switch to another branch in a hurry.

bashin the repository
# hide the edits with a labelgit stash push -m "form edits" # list: stash@{0} is the most recentgit stash list # restore and remove from the storegit stash pop # restore, keeping a copy in the storegit stash apply

Section sources

the section is written from these pages

Branching models

A branching workflow is the set of rules a team follows for opening branches and merging them into the main one. The answer to the main question is a single one: edits are made in short topic branches, and the main branch receives them through a merge after review. It is not Git that shapes the history but the team’s agreements.

A model is chosen not for its “power” but by how releases go out: continuous deployment lives with a single main branch, while versioned packages need separate release branches and maintenance of old releases.

Topic and integration branches

The gitworkflows(7) guide divides branches into two kinds. A topic branch gathers one task: a feature, a fix, an improvement. An integration branch collects finished topics and moves towards a release. Working directly in an integration branch is not advised: undoing an unfortunate commit in a shared line is hard, and the edits of several people get mixed together.

bashin the project directory
git switch -c fix/avatar-upload main# work and commit on the topicgit push -u origin fix/avatar-upload

A topic is started from the oldest integration branch it will be merged into: the fix can then be raised up the branches without taking anything extra along. This is the “merge upwards” rule: an edit is committed to the oldest branch that needs it, and the integration branches are merged into each other from time to time, bottom upwards. The move in the other direction is a cherry-pick — see the section “Rebasing and rewriting history”.

In Git itself, the different roles of integration branches are shown on four names: maint carries the commits for the next maintenance release, master — for the next release, next serves as a testing ground for trying topics out, and seen gathers what is not yet ready for inclusion. A topic reaches master gradually: first it is tried out in next, then comes the release. In your repository the names may differ — the roles matter, not the names.

The gitworkflows(7) scheme in a simplified form: in Git these are the maint, master, next and seen branches.

GitHub flow: a branch and a pull request

GitHub flow is a lightweight model built on a single main branch. An edit lives in a short branch with a descriptive name such as increase-test-timeout; the commits go to the server and leave the main branch untouched until they are merged in.

  1. Open a branch from the main one.
  2. Commit and push your edits to the server.
  3. Open a pull request: describe what is changing and what problem it solves.
  4. Work through the review comments: edit the branch and the discussion will update itself.
  5. Wait for the checks and the approval, then merge the pull request.
  6. Delete the branch: the history and the discussion remain in the pull request.

A pull request is a proposal to merge one branch into another. It gathers the whole discussion in one place: the description, the commits, the diff on the “Files changed” tab and the checks. While a pull request is marked as a draft it cannot be merged. Branch protection may require approvals and passing checks — the merge will then simply not go through.

In GitLab the same mechanism is called a merge request: review, discussion, CI/CD pipelines, the list of commits and the mergeability report — the same parts under another name. Automatic pipeline checks on pull requests are covered in the CI/CD reference, section “Triggers: when a pipeline runs”.

Trunk-based development: short branches and frequent merges

Trunk-based development takes the idea of short branches to its limit: the team has a single main branch — the trunk — and everyone merges their edits into it in small steps, often several times a day. Branches are short-lived and are opened for one task at a time; an unfinished feature is hidden behind a feature flag rather than waiting in a long-lived branch. Continuous deployment relies on precisely this rhythm.

Ways to merge a pull request

The platforms offer three ways to merge an accepted branch, and they write the history differently:

MethodWhat ends up in the main branchWhen to choose it
Merge commitall the commits of the branch and a merge commit with two parentswhen the branch history matters as it is
Squasha single new commit with all the changes of the branchwhen the main branch’s history is a list of edits, one per task
Rebasethe commits of the branch, placed on the tip of the main branch, without a merge commitwhen you want a linear history and meaningful commits inside the branch

The method is chosen at the moment of the merge and only affects how the history is written: the contents of the files come out the same. The difference is in the graph: a merge commit keeps the branching, squash and rebase leave a linear history, but rebase replays the branch’s commits one by one while squash folds them together. How moving commits around works in Git itself — see the section “Rebasing and rewriting history”.

Release branches and tags

If a product ships as a package with a version number, a release branch is kept alongside the main one: once a release has been cut from the main branch, only fixes go into its branch, and a new feature waits for the next cycle. Releases that are still supported are fixed in their branches; each release is marked with a tag — a permanent reference to a commit. This pattern is called release branching.

bashin the project directory
git switch -c release/2.3 maingit tag -a v2.3.0 -m "Release 2.3.0"git push origin release/2.3 v2.3.0

In the maint branch the Git project maintains the latest released version: the commits for the next maintenance release are prepared there. How many branches and tags your project needs is decided by the release plan, not by the tool.

Section sources

the section is written from these pages

Repository security

Secrets must never reach the repository: .gitignore keeps them out, and credential helpers store the passwords and tokens used for network access. A secret that has landed in a commit cannot be removed from history — it is revoked first. A signed commit proves authorship: on GitHub it is marked Verified.

Network credentials

Over HTTPS Git asks for a username and a password, and many servers accept a personal access token instead of the password. On request, credentials are handed over by a credential helper — an external program that keeps the password in memory, stores it on disk or puts it into the system key store. You choose the helper with the credential.helper setting; git help -a | grep credential- lists the installed ones.

HelperWhere the password is kept
cachein memory, 15 minutes by default; --timeout sets the lifetime
storeas plain text on disk
libsecret, osxkeychain, wincredthe system key store: Linux, macOS, Windows
Git Credential Managera cross-platform store, comes with Git for Windows
bashon your computer
# Linux key store; on macOS use osxkeychaingit config --global credential.helper libsecret# username for a single servergit config --global credential.https://example.com.username \  anna

A server over SSH never asks for a password at all: access is granted by keys — the setup is described in the Linux reference, section “Access and initial setup”.

A secret has landed in a commit

A revoked secret is already worthless, and the commits containing it can be left as they are. Rewriting history comes with side effects: the hashes of every commit after the edit change, a force push is required, and everyone who has already cloned has to collect a fresh copy. If a rewrite is still needed, do it in a fresh clone with git-filter-repo: the --sensitive-data-removal flag appeared in git-filter-repo 2.47.

bashin a fresh clone
# a fresh copy without foreign refsgit clone https://example.com/team/app.gitcd app# remove the file with secrets from the whole historygit-filter-repo --sensitive-data-removal --invert-paths \  --path src/module/secrets.env# filter-repo removes the origin remote: add it backgit remote add origin https://example.com/team/app.git# rewrite every branch and tag on the servergit push --force --mirror origin

After the rewrite, the history in old clones diverges from the server: colleagues move their branches onto the new history through a rebase — a single merge would bring the commits with the secret back. A commit with the secret may survive in forks, while viewing a commit by hash and links from a pull request are removed by GitHub support.

Keeping the secret out

Files holding secrets — .env, keys, certificates — go into .gitignore, and the secrets themselves live in environment variables or a secrets manager. An entry in .gitignore does not hide a file that is already tracked: untrack it first, then close the door for the future.

bashin the project directory
# stop tracking the secret and close the way backgit rm --cached .envecho ".env" >> .gitignoregit add .gitignoregit commit -m "Stop tracking .env"

Before committing, check what will go into the index: add files one by one instead of git add ., and review the staged changes in git diff --cached.

Signing commits and tags

A signed commit proves that it was made by the owner of the key: the signature is verified cryptographically, and GitHub shows a Verified badge on such a commit. You sign with GPG, SSH or S/MIME; for a single developer SSH is the simplest — the key you use to open the server will do. gpg.format selects the format, user.signingKey the key, and commit.gpgSign makes every commit signed automatically.

bashon your computer
# sign commits with an SSH keygit config --global gpg.format sshgit config --global user.signingKey ~/.ssh/id_ed25519git config --global commit.gpgSign true

git tag -s produces a signed tag; signatures are verified with the git verify-commit and git verify-tag commands or git log --show-signature. To verify an SSH signature, list the trusted keys in gpg.ssh.allowedSignersFile: without the file, verification fails with an error.

bashverifying signatures
# the keys whose signatures you trustecho "anna@example.com $(cat ~/.ssh/id_ed25519.pub)" \  > ~/.ssh/allowed_signersgit config --global gpg.ssh.allowedSignersFile \  ~/.ssh/allowed_signers# verify the last commit and the signature in the historygit verify-commit HEADgit log --show-signature -1

Hooks and untrusted repositories

Hooks are scripts that Git runs before and after its actions: pre-commit checks a commit before it is written, pre-push — before it is sent. They live in the .git/hooks directory, and git clone does not copy them: a fresh clone has no hooks, so you install them yourself or point at a directory in the repository with the core.hooksPath setting. The --no-verify flag bypasses the checks, so strict rules belong on the server — that is where the pre-receive and update hooks run.

By default Git refuses to even read the configuration of a repository you do not own, let alone run its hooks. Exceptions go into safe.directory, and the setting is read only from trusted locations — the system and global configs, not from the repository itself. A bare repository (one without a working tree) has safe.bareRepository: the value explicit allows working only with those given via --git-dir; in Git 3.0 this behaviour will become the standard.

bashon your computer
# a repository owned by someone else that you trustgit config --global --add safe.directory /srv/team/app# bare repositories — only those given explicitlygit config --global safe.bareRepository explicit

Branch protection and required checks on the server are covered in the CI/CD reference, section “Pipeline security”.

Keep Git up to date

Vulnerability fixes come out in patch releases of the current branch — X.Y.1, X.Y.2 and so on. The project has no separate long-term support, but in practice critical fixes are issued for the previous two branches as well. Install the latest patch release as early as you can — installation is described in the section “Installation and first run”.

Secrets in the pipeline and storing deployment passwords are covered in the CI/CD reference, sections “Secrets, variables and OIDC” and “Pipeline security”. Force-pushing rewritten history — see the section “Rebase and history rewriting”.

Section sources

the section is written from these pages

Common errors and diagnostics

An unexpected error or “missing” commits almost always have a predictable explanation: Git refuses to do anything that would lose work. Start with the three diagnostic commands, then find your error in the list below and fix it by the recipe.

Where to start

The order of checks runs from the current state to the history and the logs. Each command answers its own question, and together they cover almost everything you see on the screen.

  1. git status — what is happening right now: a conflict, a merge, a rebase, a divergence from the server;
  2. git log --oneline --graph --all — what the history looks like: branches, their tips and points of divergence;
  3. git reflog — where HEAD and the branches pointed after every action, including the cut-off commits.

Git usually prints the hints for the next step itself, in the output of git status. Keep the working tree clean while a merge or a rebase is in progress: an unfinished operation blocks switching branches, and undoing with losses does not bring everything back.

fatal: not a git repository

The command was run outside a repository: Git looks for the .git directory in the current directory and above and does not find it. Check where you are with pwd, and change into the project directory. There is no repository in this directory yet — create one with git init or clone an existing one. Another cause is somebody else’s directory: by default Git refuses even to read the configuration of a repository whose owner you are not; the section “Repository security” explains how to add an exception.

bashoutside a repository
pwdgit status

Push rejected: [rejected] and non-fast-forward

The server does not move a branch name if doing so would erase commits: the server has work that you do not have yet. Git marks such a ref in the output with an exclamation mark and explains: rejected, the update is non-fast-forward, and no force was requested. Fetch and integrate the other commits, then push again:

bashin the project directory
git fetch origingit rebase origin/maingit push

Instead of git rebase, git merge origin/main will do. The error is often seen after rewriting a published branch as well: the new commits do not continue the server’s history. If the work is really yours and nobody has fetched it yet, publish it with a force push — see the section “Rebase and rewriting history” for details. The server itself can also reject the push: usually that is a hook on its side or a protection against overwriting published commits.

Merge, rebase or pull conflict

Two sides changed the same lines — Git stops and leaves the markers <<<<<<<, ======= and >>>>>>> in the files. Merge, rebase, pull, cherry-pick and revert resolve conflicts by the same scheme. git status will show the list of disputed files; from there, edit the files, add them to the index and continue with the command with --continue:

bashin the project directory
git status# at the prompt in the outputgit add --resolved app.py# before Git 2.56 — plain git add# for a merge, instead of git commitgit merge --continue

The mechanics of conflicts, diff3 and rerere are covered in the section “Merging and conflicts”; a rebase in progress has its own commands — the section “Rebase and rewriting history”.

Detached HEAD

“HEAD detached” is printed in command output when HEAD points at a commit rather than a branch: new commits are attached to no branch and are left unnamed when you switch away. For looking at old code this is fine. If commits have been made in the detached HEAD, create a branch right there:

bashin the project directory
git switch -c good-surprises

Already switched to a branch? The reflog git reflog will tell you the hash of the lost commits; how to move a branch back to a found commit is covered in the section “Undoing changes”.

Branches have diverged from the server

“Your branch and 'origin/main' have diverged” is printed by git status and git pull when a branch and its server-side counterpart have both gained commits of their own. Git expects a decision: merge or rebase. Look at both lines of history with git log --oneline --graph main origin/main, then choose how to integrate:

bashin the project directory
# merge the server commits in with a merge commitgit pull --no-rebase# replay yours on top of the server’sgit pull --rebase

To make git pull refuse when the histories diverge instead of arguing about how to integrate them, keep git pull --ff-only at hand — this is how a fresh Git behaves by default when no integration method is configured.

The histories are unrelated: refusing to merge unrelated histories

The merge refuses to work without a common ancestor: the histories are unrelated, and Git does not know how to join their meanings. This happens when a local repository has been created afresh next to a cloned one, or when somebody else’s project has been added to it. If the connection is real, allow the merge explicitly — with the git merge --allow-unrelated-histories flag — and resolve conflicts as usual. Git has no setting that turns this behaviour on by default.

A lost commit

A commit that git reset --hard or a rebase cut off from a branch is still alive in the repository: it remains in the reflog and in the object database. Find it and bring it back:

bashin the repository
git reflog# a suitable line, for example a1b2c3dgit branch restore-work a1b2c3d
textexample output of git fsck
dangling commit 7281251ddd2a61e38657c827739c57015671a6b3dangling blob 218761f9d90712d37a9c5e36f406f92202db07eb

The reflog is cleaned automatically: entries for reachable commits are kept for 90 days, for unreachable ones, 30. If the reflog is empty as well, look for dangling objects with git fsck --lost-found: the command lists them and writes them to .git/lost-found — the objects have not been removed by garbage collection yet. Once you have found the hash you need, create a branch on it or add it to the current one: git cherry-pick 7281251d. How the search works is covered in more detail in the section “Undoing changes”.

Switching or merging refuses to work

Git prints an error like “Your local changes would be overwritten by checkout” (or “by merge”): the operation would overwrite files with uncommitted edits. Commit your work — or set it aside for the moment with git stash push and bring it back with git stash pop after switching. To discard the edits for good, use git restore . for files and git reset --hard for the index with the files; see the section “Undoing changes” for details.

Strange results from git log and diff after a squash merge

Long-lived branches merged with --squash or through squashing in a pull request leave no merge commit, and their base does not move. Because of this, git diff and git log with three dots show old changes as new, and conflicts have to be resolved again and again. For repeated merges of long-lived branches, use an ordinary merge commit.

An ignored file is still tracked

A rule in .gitignore applies only to untracked files: a file added before the rule appeared stays in the index. Remove it from the index, keeping it on disk:

bashin the project directory
git rm --cached app.loggit commit

The git rm --cached command does not touch the file itself — it will stop getting into commits as soon as the rule in .gitignore takes effect. Files sent out in past commits cannot be removed this way: about that, and about secrets, see the section “Repository security”.

Symptoms worth double-checking

SymptomCauseWhat to do
dangling objects in git fsckleftovers of rebases, amends and deleted branchesthis is normal; lost work can be found through them
git status does not change after editsthe edits are in a different directorycheck pwd and the repository path
local branches from the server are missingthe clone created only remote-tracking branchesgit switch feature will create a local branch
git commit prints “Committing is not possible because you have unmerged files”a conflict from an earlier operation has not been resolvedresolve it by the pattern from this section
Git will not open somebody else’s repositorythe directory belongs to another usersafe.directory — see “Repository security”

For out-of-reach work with the repository, trust ordinary push and fetch: synchronising the project directory by cloud services corrupts the Git object database, up to loss of data. If you suspect repository corruption, check it with git fsck --full and restore the data from a backup or a clone.

Section sources

the section is written from these pages

Versions and what’s new

This reference covers Git 2.56: the latest release is 2.56.0, dated 28 September 2026. New versions come out roughly every two to three months, so the version numbers and dates in this section change more often than in the other sections.

A version number consists of three parts: major, minor and patch. A minor release (2.56.0) brings new commands and options, while a patch release (2.56.1 and later) contains only bug fixes with no new features. Every few years the project gathers incompatible changes into a major release: Git 1.6.0 came out this way in 2008 and Git 2.0 in 2014, and Git 3.0 is being prepared the same way.

BranchFirst releaseLatest release
2.562.56.0 — 28 September 20262.56.0 — 28 September 2026
2.552.55.0 — 29 June 20262.55.0 — 29 June 2026
2.542.54.0 — 20 April 20262.54.0 — 20 April 2026

What has changed in 2.56

  • git add --resolved marks a path’s conflicts as resolved: you no longer need to copy the names one by one from git status. The command checks that no conflict markers are left in the file and keeps edits to other files out of the index. See the section “Merging and conflicts” for an example.
  • When the branch is behind or has diverged from its push branch, the git status hint suggests git pull <remote> <branch> with your own names instead of the generic advice.
  • fetch.followRemoteHEAD is a general default for the remote.<name>.followRemoteHEAD option: what to do with the remote’s HEAD during git fetch.
  • git log --follow follows renames of a path across a non-linear history, when the file was renamed differently in different branches.
  • git log --graph indents root commits so that they do not look like a continuation of another branch higher up in the graph.
  • A typo in a command is recognised: Git treats git push origin/main and git branch origin main as a likely mistake and suggests the right variant.

Security updates

A vulnerability is announced on the official Git mailing list on the day of the release that fixes it. The releases of 2.55 and 2.56 mention no vulnerabilities; in recent years, CVEs were fixed by series of simultaneous patch releases covering several branches at once. Install Git from your distribution’s packages or build the new release yourself — then check the version number with git --version.

bashUbuntu and Debian
sudo apt updatesudo apt install git

Plans for Git 3.0

The list of future incompatible changes is open: the “Upcoming breaking changes” document announces decisions in advance, and Git 3.0 has no release date yet. Planned for new repositories:

  • the default branch — main instead of master; a warning about this has been shown since 2020, and the name matches the setting used by most hosting providers;
  • the reftable ref format instead of files and directories inside .git: writing many refs is faster, and there are fewer problems on Windows and macOS;
  • the SHA-256 hash algorithm instead of SHA-1, deprecated since 2011; the sha1 format is not removed, and old repositories will keep working;
  • safe.bareRepository=explicit by default: Git will refuse to work with a bare repository (a repository without a working tree) found higher up in the directory tree unless it is specified with --git-dir or GIT_DIR — this neutralises a repository with its own hooks planted by an attacker;
  • the removal of grafts, the old mechanism for overriding a commit’s parents; the replacement already exists: git replace.

None of these changes touch existing repositories: the new values are applied only by git init. The last release before Git 3.0 will be declared long-term: at least four release cycles of bug fixes are promised for it, and six of security updates. The section “Installation and first run” covers installing and updating Git.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Git” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61