Configuration
git config [--system | --global | --local] <key> [<value>]
Reads and writes configuration variables that control all aspects of Git behaviour. Variables can be stored at three distinct hierarchical levels: system, global user, and local repository. Each level overrides the previous one. Variables set without an explicit level are written to the local .git/config file.
OptionEffect
--systemOperates on the system configuration file (/etc/gitconfig), applicable to all users on the machine.
--globalOperates on ~/.gitconfig: applies to all repositories of the current user.
--localOperates on .git/config of the current repository (default behaviour).
--listDisplays all configuration variables read from all active levels.
--show-originShows next to each value the configuration file it originates from.
-f <file>Operates on an arbitrary configuration file.
--unsetRemoves the specified variable from the targeted configuration file.
Common variables include user.name, user.email, core.editor, init.defaultBranch, pull.rebase and credential.helper.
git help <command>
Displays the man page for the specified Git command. Available offline. Each Git command also accepts --help for the same result, and -h for a short summary of available options.
Initialisation & cloning
git init [--bare] [--shared] [directory]
Creates a new Git repository by initialising the .git subdirectory in the current or specified directory. This directory holds all objects, references and metadata for the repository. If no files are present, the working tree is empty and no commit exists yet.
OptionEffect
--bareCreates a bare repository with no working tree. Used for server-side repositories intended to be shared.
--sharedEnables group write permissions on the repository. Useful for repositories shared via multi-user SSH access.
git clone <url> [<target-directory>]
Retrieves a full copy of an existing Git repository, including its entire history. The remote repository is automatically registered under the short name origin. A local tracking branch is created for each remote branch, and the main branch is checked out in the working tree. Supported protocols include https://, ssh://, git:// and local paths.
OptionEffect
--bareClones the repository as a bare repository, without a working tree.
--depth <n>Shallow clone: retrieves only the last n commits (truncated history).
-o <name>Uses name instead of origin for the remote repository.
-b <branch>Checks out the specified branch rather than the default branch.
Basic snapshots
git add <file|directory|pattern> ...
Places changes in the staging area (index) to include them in the next commit. Its effect is closer to "add this content for the next snapshot" than a simple addition to the project. It is used to start tracking new files, stage modified files, and mark merge conflicts as resolved. If a directory is specified, the command recursively stages all files it contains.
OptionEffect
-A / --allStages all changes: new, modified and deleted files across the entire working tree.
-p / --patchInteractive hunk-by-hunk mode: allows partial selection of changes within a file to stage.
-i / --interactiveLaunches interactive staging mode via a text menu.
-u / --updateStages only already-tracked files (modified or deleted), without adding new files.
-n / --dry-runSimulates the operation without modifying the index.
-f / --forceAllows adding files normally ignored by .gitignore rules.
git status [-s | --short] [-b]
Displays the state of the working tree and staging area relative to the last commit. Identifies modified, staged or untracked files, and reminds you of commands to act on each category. Also shows the current branch and its ahead/behind status relative to its tracked remote branch.
OptionEffect
-s / --shortDisplays compact one-line-per-file output: status code letters on the left.
-b / --branchIncludes branch information even in short mode.
git diff [--staged] [<commit>] [--] [<path>...]
Displays line-by-line differences (patch) between different states of the repository. Without arguments, compares the working tree with the index (unstaged changes). With --staged or --cached, compares the index with the last commit (staged changes that will be part of the next commit). Can also compare two arbitrary commits or a commit with the working tree.
OptionEffect
--staged / --cachedCompares the index to the last commit: shows what will be committed.
--checkIdentifies and lists whitespace errors (trailing spaces, mixed tabs/spaces).
--statStatistical summary: modified files and number of added or removed lines.
-wIgnores all whitespace changes.
git difftool launches an external graphical tool (Araxis, vimdiff, etc.) to visualise the same differences.
git commit [-m <message>] [-a] [--amend] [-v]
Records the current state of the index as a new commit object in the local repository. Each commit contains a snapshot of staged content, author and committer metadata, the date, the commit message, and a pointer to the parent commit(s). Without a message option, opens the configured editor to enter the message.
OptionEffect
-m <message>Specifies the commit message directly on the command line.
-aAutomatically stages all already-tracked files before committing, bypassing git add.
--amendReplaces the most recent commit with a new commit incorporating the current index and/or a modified message. The original commit is discarded.
-vIncludes the full diff in the message editor as a comment.
--amend rewrites history. Do not use it on commits already pushed to a shared repository.
git rm [-f] [--cached] <file>...
Removes files from the index and working tree in a single operation, recording the removal for the next commit. Unlike a plain system deletion, the removal is staged and will be included in the next commit.
OptionEffect
-f / --forceForces removal even if the file has been modified or staged since the last commit.
--cachedRemoves the file from the index only, without deleting it from the working tree. Useful to stop tracking an accidentally staged file.
git mv <source> <destination>
Renames or moves a file and stages the change for the next commit. Equivalent to running mv, git rm and git add in sequence. Git detects renames implicitly anyway; this command simply simplifies the operation to one step.
History
git log [-p] [--stat] [--pretty=<format>] [--graph] [--oneline] [-n] [--since] [--author] [-S] [--] [<path>]
Displays the commit history of the repository in reverse chronological order. For each commit, shows the SHA-1 checksum, author name and email, date, and commit message. Offers a wide range of filtering and output formatting options.
OptionEffect
-pShows the full diff (patch) for each commit.
--statShows summarised statistics (modified files, insertions, deletions) below each commit.
--shortstatShows only the summary statistics line.
--name-onlyShows the list of modified file names after each commit's information.
--name-statusShows file names with their modification code (A, M, D…).
--abbrev-commitShows only the first few characters of the SHA-1 instead of the full checksum.
--onelineShows each commit on a single line (abbreviated SHA + message title).
--graphAdds an ASCII graph of branches and merges alongside the history.
--decorateShows branch and tag labels pointing to each commit.
--pretty=format:"…"Custom output format using specifiers (%H, %an, %s, %ar, etc.).
-<n>Limits output to the n most recent commits.
--since / --afterFilters commits after the specified date.
--until / --beforeFilters commits before the specified date.
--authorFilters by author name.
--grepFilters by commit message content.
-S <string>Filters commits whose changes add or remove the specified string in the code.
--no-mergesExcludes merge commits from the output.
--allShows history from all branches, not only the current branch.
git show [<object>]
Displays detailed information about a Git object: commit (metadata and diff), annotated tag (creator information and associated commit), tree or blob. Without arguments, shows the last commit on the current branch.
Undoing
git restore [--staged] <file>...
Introduced in Git 2.25, a dedicated command for resetting files. Without options, resets a file in the working tree to its last committed state, discarding unstaged local changes. With --staged, unstages a file (removes it from the staging area) without touching the working tree.
OptionEffect
--stagedActs on the index: unstages the specified file without modifying the working tree.
--source <tree>Restores the file from the specified Git tree rather than the last commit.
Without --staged, all uncommitted local changes to the file are permanently lost.
git reset [--soft | --mixed | --hard] [<commit>] [--] [<file>...]
A versatile command for moving the HEAD pointer and/or modifying the state of the index and working tree. With a file path, unstages the specified file (equivalent to git restore --staged). With a commit as target, repositions HEAD and acts on the index and working tree according to the chosen mode. It is the foundation of undo and history-rewriting operations in Git.
ModeEffect on HEAD
--softMoves HEAD to the target commit. Index and working tree remain unchanged. Changes appear as "to be committed".
--mixed (default)Moves HEAD and resets the index. Working tree remains unchanged. Changes appear as unstaged.
--hardMoves HEAD, resets the index AND overwrites the working tree. All local changes are permanently lost.
The --hard option is destructive and irreversible on uncommitted data.
git revert <commit>
Creates a new commit that exactly reverses the changes introduced by the specified commit. Unlike git reset, does not rewrite history: the reverted commit remains in the graph. The safe method to undo commits already shared on a public repository.
Branches
git branch [-v] [-a] [--merged | --no-merged] [--move | -d | -D] [<name>]
Manages local branches. Without arguments, lists local branches, marking the current branch with an asterisk. A Git branch is simply a lightweight pointer to a commit; creating and deleting branches costs almost nothing.
OptionEffect
-vShows the last commit of each branch with its message.
-vvAlso shows the tracked remote branch and ahead/behind status.
-aAlso lists remote branches (prefixed remotes/).
-d <branch>Deletes the branch if it has been fully merged into the current branch.
-D <branch>Forces deletion of the branch even if commits have not been merged.
--mergedFilters the list to branches whose work has already been integrated into the current branch.
--no-mergedFilters the list to branches containing work not yet merged.
--move / -mRenames the branch locally.
-u <remote>/<branch>Associates the local branch with a remote branch (tracking / upstream branch).
git checkout [-b <new-branch>] [<branch> | <commit>] [-- <file>]
The historic dual-purpose command: switches to an existing branch (moves HEAD and updates the working tree) or restores files in the working tree. Since Git 2.23, its two functions are better separated by git switch and git restore. When switching branches, Git resets the working tree to the state of the last commit on the target branch.
OptionEffect
-b <name>Creates a new branch and switches to it immediately in a single operation.
--trackCreates a local branch that automatically tracks the specified remote branch.
-- <file>Restores the file in the working tree to its state in the index or current commit, discarding local changes.
git switch [-c <new-branch>] [<branch>] [-]
Introduced in Git 2.23 to cleanly separate the branch-switching function from file restoration. Allows changing branches, creating a new one and switching to it, or returning to the previously checked-out branch.
OptionEffect
-c <name> / --createCreates a new branch and switches to it.
- (dash)Returns to the previously checked-out branch.
git merge [--no-ff] [--squash] <branch>
Integrates the history and changes of a branch into the current branch. If the target branch is a direct ancestor of the branch to merge, Git performs a fast-forward by simply moving the pointer. Otherwise, Git performs a three-way merge by creating a new merge commit with two parents. In case of conflict, the merge is interrupted and conflicting files are marked for manual resolution.
OptionEffect
--no-ffAlways creates a merge commit, even when a fast-forward would be possible.
--squashCondenses all commits from the merged branch into a single set of staged changes, without creating an automatic merge commit.
--abortAborts an in-progress merge and restores the state before the merge attempt.
git mergetool [--tool=<tool>]
Launches a graphical merge conflict resolution tool. Git detects and suggests available tools on the system (opendiff, kdiff3, vimdiff, emerge, etc.). After resolving each conflict in the tool, the file is marked as resolved in the index.
OptionEffect
--tool=<name>Forces the use of the specified tool rather than the default.
--tool-helpDisplays the list of merge tools available on the system.
git rebase [-i] [--onto <newbase>] [<upstream>] [<branch>]
Replays commits from a branch onto a new base, producing a linear history. Identifies the common ancestor between the current branch and the target, extracts the diffs of each commit, resets the branch to the target, then re-applies each diff in order. Unlike merging, creates no merge commit; the resulting history is more readable but rewrites SHA-1 identifiers.
OptionEffect
-i / --interactiveInteractive mode: allows reordering, squashing, rewording or dropping commits before replaying them.
--onto <newbase>Replays commits onto an arbitrary base different from upstream, allowing transplantation of a branch onto another.
--abortInterrupts an in-progress rebase and restores the original state.
--continueContinues the rebase after resolving a conflict.
--skipSkips the current conflicting commit and moves to the next.
Never rebase commits already pushed to a public repository. Rebasing rewrites SHA-1s and forces collaborators to re-merge their work.
Remote repositories
git remote [-v] [add | remove | rename | show | prune] ...
Manages references to remote repositories (short names and associated URLs). Without arguments, lists the short names of registered remote repositories. Remote repositories are versions of your project hosted elsewhere (internet, local network, or even a local path).
Sub-commandEffect
-vShows the fetch and push URLs of each registered remote.
add <name> <url>Registers a new remote under the specified short name.
remove <name>Removes the remote reference, along with all associated tracking branches and configuration.
rename <old> <new>Renames the remote and updates all corresponding tracking branch names.
show <name>Shows detailed information about the remote: URLs, tracked branches, push and pull configuration.
prune <name>Removes local remote references that no longer exist on the remote server.
git fetch [<remote>] [--all] [--prune]
Retrieves from the remote repository all new data (commits, branches, tags) not yet present locally. Updates only remote-tracking branches (e.g. origin/master), without touching local branches or the working tree. Merging remote data into local work must be done manually with git merge.
OptionEffect
--allFetches from all configured remote repositories in a single operation.
--pruneRemoves local tracking branches that no longer have a counterpart on the remote.
git pull [--rebase] [<remote>] [<branch>]
Combines git fetch immediately followed by git merge (or git rebase depending on configuration). Retrieves remote changes from the configured tracking branch and integrates them into the current local branch. If pull.rebase is set to true, performs a rebase instead of a merge.
OptionEffect
--rebaseRebases the local branch onto the remote branch rather than merging.
--no-rebaseForces a merge even if pull.rebase is set to true.
git push [<remote>] [<local-branch>[:<remote-branch>]] [--tags] [--delete] [--force] [-u]
Transfers commits from the local branch to the specified remote repository. The push is rejected if the remote history has diverged (someone pushed in the meantime): you must first fetch and merge the remote changes. Tags are not pushed automatically; they must be specified explicitly.
OptionEffect
-u / --set-upstreamRecords the remote branch as the upstream of the local branch, simplifying future pushes and pulls.
--tagsPushes all local tags (lightweight and annotated) not yet present on the remote.
--follow-tagsPushes only annotated tags associated with pushed commits.
--delete <branch>Deletes the specified branch or tag on the remote repository.
--force / -fForces the push even if it is not a fast-forward (overwrites remote history). Dangerous in a shared environment.
<local>:<remote>Refspec: pushes the local branch to a remote branch with a different name.
--force overwrites remote history. Only use it with absolute certainty in a controlled context.
Tags
git tag [-a] [-m <message>] [-d] [-l <pattern>] <name> [<commit>]
Creates, lists or deletes tags to mark important points in history (published versions, milestones). Git distinguishes two tag types: lightweight (a simple pointer to a commit) and annotated (full objects with metadata, message and optional GPG signature). Annotated tags are recommended for official releases. Tags are not pushed automatically with git push.
OptionEffect
-aCreates an annotated tag, stored as a Git object with its own SHA-1.
-m <message>Specifies the annotated tag message directly on the command line.
-sCreates a GPG-signed tag.
-d <name>Deletes the tag locally (does not delete it on remote repositories).
-l <pattern>Filters the tag list by a glob pattern (required if a pattern contains wildcards).
<commit>Tags a specific commit rather than HEAD (after-the-fact tagging).
Stashing
git stash [push | pop | list | apply | drop | show | branch]
Temporarily saves working tree and index changes onto a stack, without creating a commit. The working tree is reset to the last commit state, allowing a context switch without committing unfinished work. Stashes can be re-applied later, including on other branches.
Sub-commandEffect
push / (default)Pushes current changes (working tree and index) onto the stash stack.
popRe-applies the most recent stash and removes it from the stack.
apply [stash@{n}]Re-applies a stash without removing it from the stack.
listDisplays the list of all stacked stashes with their description.
drop [stash@{n}]Removes a specific stash from the stack without applying it.
show [stash@{n}]Shows the diff of the specified stash.
branch <branch>Creates a new branch from the commit where the stash was created, then applies the stash onto it.
Search and debugging
git grep [-n] [-c] [-p] <pattern> [<tree>]
Searches for a pattern (regular expression or literal) in repository files, with the option to target a specific commit or tree rather than the working tree. Faster than standard grep on large repositories because it only examines tracked files.
OptionEffect
-nShows line numbers of matches.
-cShows only the match count per file.
-pShows the name of the function containing each match.
--and / --orCombines multiple patterns with logical operators.
git bisect [start | good | bad | reset | run <script>]
Binary search tool through history to locate the commit that introduced a bug. Git automatically navigates history by bisection, reducing the search to O(log n) commits to test. Each commit is marked good or bad until the first defective commit is isolated. Can be fully automated with a test script.
Sub-commandEffect
startStarts a binary search session.
bad [<commit>]Marks the current (or specified) commit as bad.
good [<commit>]Marks the current (or specified) commit as good.
resetEnds the session and returns to the initial branch.
run <script>Automatically runs the script for each tested commit. Exit 0 = good, exit 1 = bad.
git blame [-L <start>,<end>] <file>
Displays each line of a file annotated with the commit that last introduced it, as well as the author and date. Allows quickly identifying who modified a particular line of code and in which commit.
OptionEffect
-L <start>,<end>Restricts annotation to the specified line range.
-CDetects lines copied from other files.
--show-statsDisplays additional statistics at the end.
History rewriting
git filter-branch [--tree-filter | --env-filter | --commit-filter | --msg-filter] <filters> [<rev-list>]
Rewrites the entire history by applying scripted filters to each commit. Allows removing a file from the entire history, modifying author metadata, changing commit messages in bulk, or splitting a subdirectory into an independent repository. Slow and irreversible operation; prefer git-filter-repo for recent versions.
Rewrites all SHA-1s in history. Only use before publishing a repository or in full coordination with all contributors.
git cherry-pick <commit>...
Re-applies the changes introduced by one or more specific commits onto the current branch, creating equivalent new commits. Useful for importing a bug fix from one branch to another without merging the entire source branch.
OptionEffect
-n / --no-commitApplies changes to the working tree and index without automatically creating a commit.
-xAppends a reference to the original source commit in the commit message.
git rerere [clear | forget | diff | status | remaining | gc]
"Reuse recorded resolution": memorises merge conflict resolutions already performed and automatically re-applies them when the same conflict recurs. Particularly useful on topic branches that are regularly rebased onto master. Must be enabled with git config rerere.enabled true.
Submodules
git submodule [add | init | update | status | foreach | sync]
Manages submodules: Git repositories nested inside a parent repository, pinned to a specific commit. Allows including and managing external dependencies (libraries, tools) while keeping their histories separate. The parent repository records only the URL and SHA-1 of the commit used for each submodule.
Sub-commandEffect
add <url> [path]Adds a new submodule: clones the repository and records its reference in .gitmodules.
initInitialises the local configuration of submodules declared in .gitmodules after a clone.
update [--remote] [--recursive]Checks out the recorded commit for each submodule. With --remote, fetches the latest commit on the tracking branch.
status [--recursive]Shows the status of each submodule (checked-out commit vs recorded commit).
foreach <command>Runs a shell command in each submodule.
syncUpdates remote repository URLs for submodules from .gitmodules.
Administration
git gc [--aggressive] [--prune=<date>]
Runs repository maintenance tasks: compresses loose objects into pack files, removes unreachable objects (orphans, deleted refs), and optimises Git's internal structures for better performance. Git may run this command automatically in the background.
OptionEffect
--aggressiveMore thorough but slower optimisation: rewrites pack files with better compression.
--prune=<date>Removes unreachable objects older than the specified date (default: 2 weeks).
git fsck [--full] [--lost-found]
Verifies the integrity of the Git object database and detects corrupted data or orphaned objects (dangling objects). Orphaned objects are commits, trees or blobs not referenced by any branch or tag; they may represent recoverable lost work.
OptionEffect
--fullAlso checks pack files, not only loose objects.
--lost-foundWrites found orphaned objects to .git/lost-found/.
--danglingShows objects that exist but are not referenced by anything (default: enabled).
git bundle [create | verify | list-heads | unbundle]
Packages Git objects and references into a portable binary file (bundle), allowing Git history to be transferred via network-free media (USB drive, email attachment). A bundle can be used as a remote repository for git fetch or git clone.
Sub-commandEffect
create <file> <rev-list>Creates a bundle containing the specified objects and references.
verify <file>Verifies that a bundle is valid and that prerequisites are satisfied locally.
list-heads <file>Lists the references contained in the bundle.
unbundle <file>Imports the bundle's objects into the current repository.
git replace <object> <replacement>
Creates a replacement reference that causes Git to treat one object as if it were another, without rewriting history. Useful for grafting separate histories or correcting errors in old commits without modifying SHA-1s. Replacements are stored in refs/replace/.
Plumbing commands (low level)
git ls-tree [-r] <tree>
Displays the contents of a Git tree object (list of files and subdirectories with their modes, types and associated SHA-1s). A plumbing command used to inspect the repository's internal objects directly.
git cat-file [-t | -s | -p] <object>
Displays the content, type or size of a Git object (blob, tree, commit, tag) identified by its SHA-1 or a symbolic reference. A fundamental command for inspecting the repository's internal objects.
OptionEffect
-tShows the object type (blob, tree, commit, tag).
-sShows the object size in bytes.
-pDisplays the object content in a human-readable format suited to its type.
git hash-object [-w] [-t <type>] <file>
Computes the SHA-1 of a file according to the Git object format and optionally stores it in the object database. A plumbing command illustrating how Git generates identifiers for its objects.
OptionEffect
-wWrites the object to the repository database rather than simply displaying its SHA-1.
-t <type>Specifies the type of object to create (blob, tree, commit).
git write-tree
Creates a tree object in the Git database from the current index contents and returns its SHA-1. A plumbing command used in low-level scripts to manually construct commits.
git update-ref <ref> <value>
Updates a Git reference (branch, tag or any refs/) to point to the specified SHA-1. The safe plumbing method for manipulating references, preferable to directly editing files in .git/refs/.
git ls-remote [<remote>]
Displays the complete list of references (branches, tags, HEAD) of a remote repository with their corresponding SHA-1s, without downloading any objects. A plumbing command for querying the state of a remote repository without fetching.