Git commands

A working reference for the Git command line, checked against the Git 2.56.0 manual pages on git-scm.com. Rows are literal command lines grouped by task: setup, staging and committing, branching, remotes, history, undoing, stashing, tags, rebasing, worktrees and submodules. Words in capitals are placeholders to replace; lowercase names such as origin, master and topic come from the manual's own examples. Plumbing commands and most options are left out: git help COMMAND opens the full manual page of any command.

194 commands in 15 sections. Checked row by row against Git 2.56.0 manual: git(1), the top-level manual page on . Edited by Jay.

Setup and configuration 9

The older option forms of git config (a bare name to read, name and value to write, --list) are deprecated; the manual recommends the get, set and list subcommands shown here.

CommandWhat it does
git config --global user.name "Your Name Comes Here"Set your author nameRun it once before the first commit; the name goes into the author field of every commit you make.
git config --global user.email [email protected]Set your author emailWith --global the value goes into your per-user configuration file, not into this repository.
git config listList all settingsPrints every variable found in the system, per-user and repository files together with its value.
git config get NAMERead one settingPrints the last value stored for the variable and returns exit code 1 when it is not set.
git config set NAME VALUEChange a settingWrites to the repository's own config by default; add --global to store it for your user account.
git helpList common commandsWith no arguments it prints the synopsis and the most commonly used commands.
git help COMMANDOpen a command manual pageBrings up the manual page of that command, by default with the man program.
git versionShow the installed versionPrints the Git version number; --build-options adds details of how it was built.
git --versionShow version (option form)Converted internally into git version, so both print the same thing.

Starting a repository 6

CommandWhat it does
git initCreate a repository hereAdds a .git directory to the current folder and overwrites nothing when one is already there.
git init -b BRANCH-NAMEChoose the first branch nameOverrides the default initial branch name, which the manual gives as master until Git 3.0 switches to main.
git clone REPOSITORYClone a repositoryCreates a new directory, a remote-tracking branch for every remote branch, and checks out the initial branch.
git clone --depth DEPTH REPOSITORYMake a shallow cloneTruncates history to the given number of commits and implies --single-branch.
git clone -b NAME REPOSITORYClone and check out a branchChecks out the named branch, not the remote default; a tag name gives a detached HEAD.
git clone --recurse-submodulesClone with submodulesInitialises and clones every submodule once the main clone is finished.

Staging and committing 17

CommandWhat it does
git statusShow working tree statusLists staged changes, unstaged changes and untracked files.
git status -sShow status in short formatPrints one line per path with a two-letter status code.
git add PATHSPECStage filesAdds the current content of the matching files to the index, ready for the next commit.
git add .Stage the current directoryStages everything under the directory you are in, new files included.
git add -AStage all changesAlso records deletions; without a pathspec it covers the entire working tree.
git add -uStage tracked files onlyStages modifications and deletions of files Git already tracks and adds no new files.
git add -pStage selected hunksWalks through the changes hunk by hunk so that only part of a file is staged.
git commitCommit staged changesOpens your editor for the message when none is supplied on the command line.
git commit -m MSGCommit with a messageTakes the message from the command line; repeating -m adds further paragraphs.
git commit -aCommit all tracked changesStages modified and deleted tracked files first; files never added stay out.
git commit --amendReplace the last commitCreates a new commit in place of the branch tip, reusing its message unless you change it.
git commit --amend --no-editAmend without editing messageAdds the staged changes to the last commit and keeps its message as it is.
git rm PATHSPECDelete tracked filesDeletes the files on disk and stages their removal for the next commit.
git rm --cached PATHSPECStop tracking a fileRemoves the path from the index only; the file itself stays on disk.
git mv SOURCE DESTINATIONRename or move a fileRenames the file, directory or symlink and updates the index in the same step.
git guiOpen the graphical interfaceTcl/Tk tool for making and amending commits, creating branches, merging and pushing.
git citoolOpen the commit dialogGraphical one-shot commit: review changes, stage them, type a message and record the commit.

Comparing changes 9

CommandWhat it does
git diffShow unstaged changesShows edits not yet staged: the working tree against the index.
git diff --cachedShow staged changesCompares the index with the last commit: what is staged for the next one.
git diff --stagedShow staged changes (synonym)Does exactly what --cached does; both names are accepted.
git diff HEADShow all uncommitted changesCompares the working tree with the last commit, so staged and unstaged edits show together.
git diff topic masterCompare two branchesShows the differences between the tips of the two branches.
git diff topic...masterDiff since the branch pointThree dots show what changed on master after topic was started from it.
git diff --statSummarise changes per filePrints a diffstat, a per-file summary of how much changed, in place of the patch text.
git difftoolOpen changes in a diff toolTakes the same arguments as git diff and opens each changed file in an external tool.
git range-diff RANGE1 RANGE2Compare two commit rangesShows how two versions of a patch series differ, for example a branch before and after a rebase.

Branching and merging 21

CommandWhat it does
git branchList local branchesWith no arguments it lists local branches and marks the current one with an asterisk.
git branch BRANCH-NAMECreate a branchPoints the new branch at the current HEAD but leaves you on the branch you were on.
git branch -d BRANCH-NAMEDelete a merged branchRefuses unless the branch is fully merged into its upstream, or into HEAD when it has none.
git branch -D BRANCH-NAMEForce-delete a branchShortcut for --delete --force: removes the branch whatever its merge status.
git branch -m OLD-BRANCH NEW-BRANCHRename a branchRenames the branch together with its configuration and reflog.
git branch -aList local and remote branchesAdds the remote-tracking branches to the usual list of local ones.
git branch --mergedList merged branchesLists only branches whose tips are reachable from HEAD, or from a commit you name.
git branch --show-currentPrint the current branchPrints the branch name alone, or nothing in detached HEAD state.
git switch BRANCHSwitch to a branchMakes the working tree and index match that branch; later commits are added to it.
git switch -c NEW-BRANCHCreate and switch to a branchCreates the branch at the current commit, or at a start point you add, and switches to it.
git switch -Switch to the previous branchReturns to the branch you were on before the last switch.
git checkout BRANCHSwitch branches with checkoutOne command with two modes, switching branches and restoring files; git switch covers the first.
git checkout -b NEW-BRANCHCreate and check out a branchStarts the branch at the current commit unless a start point follows, then checks it out.
git merge COMMITMerge into the current branchBrings the history of the named branch or commit into the current branch, with a merge commit when needed.
git merge --no-ffAlways create a merge commitRecords a merge commit even when the branch could simply be fast-forwarded.
git merge --squashSquash a branch into one changeApplies the combined changes to the working tree and index without committing or recording a merge.
git merge --abortCancel a conflicted mergeStops the merge and tries to put the working tree back as it was before.
git merge --continueFinish a mergeConcludes the merge once every conflict has been resolved and staged.
git mergetoolResolve conflicts in a toolOpens each conflicted file in a merge utility; typically run after a merge stops on conflicts.
git merge-tree BRANCH1 BRANCH2Merge without touching filesPerforms the merge without reading or writing the working tree or index and makes no commit.
git rerereReuse recorded resolutionsReplays how you resolved a conflict when the same one returns; needs rerere.enabled set.

Remotes and syncing 19

A plain git pull only fast-forwards. When your branch and the remote branch have diverged it fails until you pick --rebase or --no-rebase, or set pull.rebase or pull.ff.

CommandWhat it does
git remoteList remotesWith no arguments it prints the names of the existing remotes.
git remote -vList remotes with URLsShows the URL after each remote name.
git remote add NAME URLAdd a remoteRegisters the repository under that name so git fetch can update its remote-tracking branches.
git remote remove NAMERemove a remoteDeletes the remote together with its remote-tracking branches and settings.
git remote set-url NAME NEWURLChange a remote URLReplaces the URL stored for the remote; --push changes the push URL only.
git fetchDownload from a remoteUpdates the remote-tracking branches; the remote defaults to origin or to the upstream of the current branch.
git fetch --allFetch from all remotesFetches from every configured remote in one run.
git fetch --pruneFetch and prune stale branchesAlso removes remote-tracking references that no longer exist on the remote.
git pullFetch and integrateRuns git fetch, then integrates the upstream branch into the current one; by default only as a fast-forward.
git pull --rebasePull with rebaseRebases your local commits on top of the fetched branch in place of a merge.
git pull --ff-onlyPull by fast-forward onlyThe default mode: updates by fast-forward and stops with an error if the two branches have diverged.
git pull --no-rebasePull with a mergeMerges the fetched branch into yours, which records a merge commit when the two have diverged.
git pushUpload commits to a remoteWith no arguments it normally pushes the current branch to its upstream branch of the same name.
git push origin mainPush a branch to a remoteUpdates main on the remote called origin from your local main.
git push --set-upstream REMOTE BRANCHPush and set upstreamShort form -u; records the remote branch as the upstream that a bare git pull then uses.
git push --force-with-leaseForce push safelyOverwrites the remote branch only if it still points where your remote-tracking ref says it does.
git push --forceForce pushDisables the ancestry check, so commits on the remote that you do not have are lost.
git push --tagsPush all tagsSends every local tag along with the refs you name.
git push origin :experimentalDelete a remote branchAn empty source before the colon deletes the matching branch on origin.

Inspecting history 28

CommandWhat it does
git logShow commit historyLists the commits reachable from HEAD, newest first, with author, date and message.
git log --onelineShow one line per commitShorthand for --pretty=oneline --abbrev-commit: an abbreviated hash and the subject.
git log --graphDraw the branch graphDraws the branch and merge structure as a text graph beside the commits.
git log -pShow patches in the logPrints the diff each commit introduces below its log message.
git log --follow builtin/rev-list.cFollow a file across renamesHistory of one file, continued past the point where it got its present name.
git log -S'foo()'Find commits changing a stringLists commits whose diff changes how many times the string occurs (the pickaxe search).
git log --since="2 weeks ago" -- gitkLimit log by date and pathOnly commits from the past fortnight that touch the file named after the two dashes.
git log -3Limit the number of commitsStops after the three most recent commits; any number works.
git log master..testList commits on one branch onlyLists the commits that test has and master does not.
git showShow a commitDefaults to HEAD: prints the log message and the textual diff of that commit.
git show next~10:Documentation/READMEPrint a file from a commitREV:PATH names a file as it was in that commit; here ten commits before the tip of next.
git blame FILEShow who changed each lineAnnotates every line with the commit and author that last modified it.
git blame -L 40,60 fooBlame a line rangeRestricts the annotation to lines 40 to 60 of the file foo.
git annotate FILEAnnotate file linesSame data as git blame in a slightly different output format; kept for older scripts.
git shortlogSummarise commits by authorGroups commit titles under each author, the layout used in release announcements.
git shortlog -s -nRank authors by commit countPrints only a count per author, sorted from most to fewest.
git describeName a commit after a tagPrints the nearest reachable tag, plus a commit count and abbreviated hash when the commit itself is untagged.
git reflogShow where HEAD has beenLists recent updates to HEAD, including branch switches; name a ref to see its log.
git grep PATTERNSearch tracked filesLooks for the pattern in the tracked files of the working tree and prints each hit.
git grep -nSearch with line numbersPrefixes every match with its line number.
git bisect startStart a bisect sessionBegins a binary search for the commit that introduced a bug; mark one bad and one good commit next.
git bisect badMark a commit as badSays the version you just tested is broken; Git then checks out the next commit to test.
git bisect goodMark a commit as goodSays the version you just tested works correctly.
git bisect resetEnd a bisect sessionCleans up and returns to the commit that was checked out before the search started.
git show-branchCompare branch historiesDraws the commit ancestry of several branches side by side, 26 branches and commits at most.
git whatchangedShow logs with raw diffsLike git log with raw diff output and merges skipped; kept for historical reasons.
gitkOpen the history browserGraphical viewer for the commit graph, each commit's details and the files it changed.
git instawebBrowse the repository in gitwebSets up gitweb and a web server so the local repository can be browsed in a browser.

Undoing changes 16

Three similarly named commands do different jobs: git reset moves the branch tip, git restore only changes files in the working tree or index, and git revert adds a new commit that reverses an earlier one.

CommandWhat it does
git restore PATHSPECDiscard working tree changesOverwrites the files with their staged version, so unstaged edits to them are lost.
git restore .Discard changes in this directoryApplies the restore to every file under the directory you are in.
git restore --staged PATHSPECUnstage filesResets the index entries to HEAD; the edits stay in the working tree.
git restore --source master~2 MakefileRestore a file from a commitTakes the file from another commit, here two commits before the tip of master.
git resetUnstage everythingDefaults to --mixed and HEAD: the index is reset while files in the working tree stay as they are.
git reset HEAD^Undo the last commit, keep editsMoves the branch back one commit and unstages its changes; the files keep their content.
git reset --soft HEAD^Undo the last commit, keep it stagedMoves the branch back one commit and leaves the index and working tree untouched.
git reset --hardDiscard all uncommitted changesResets the index and overwrites tracked files to match HEAD, so local changes are lost.
git reset --hard HEAD^Delete the last commitDrops the newest commit from the branch together with every uncommitted change.
git reset --hard HEAD~3Delete the last three commitsRewinds the branch and discards those changes; not for commits already given to others.
git reset --hard ORIG_HEADUndo a merge or pullReturns the branch to where it was before the operation and throws away local changes.
git revert COMMITReverse a commitAdds a new commit that undoes the named one, leaving existing history as it is.
git revert HEAD~3Revert an older commitUndoes the fourth-newest commit of the branch in one new commit.
git clean -fDelete untracked filesRemoves untracked files from the current directory down; -f is required unless clean.requireForce is false.
git clean -nPreview what clean would deleteDry run: lists the untracked files without removing anything.
git clean -dInclude untracked directoriesLets clean go into untracked directories, which it otherwise leaves alone.

Stashing 9

Stash entries are named with reflog syntax: stash@{0} is the newest, stash@{1} the one before it, and a bare number N means stash@{N}.

CommandWhat it does
git stashStash uncommitted changesSaves staged and unstaged changes to tracked files and resets the working tree to HEAD.
git stash push -m MESSAGEStash with a descriptionSaves the changes together with your own description of the stashed state.
git stash -uStash untracked files tooIncludes untracked files in the entry and then removes them from the working tree.
git stash listList stash entriesShows every entry, newest first as stash@{0}.
git stash show -p stash@{1}Show a stash as a patchPrints the full diff of the second-newest entry.
git stash popRestore and drop the latest stashApplies the newest entry and removes it from the list, unless the apply ends in conflicts.
git stash applyRestore a stash and keep itWorks like pop but leaves the entry in the stash list.
git stash dropDelete a stash entryRemoves the latest entry, or the one you name, without applying it.
git stash clearDelete all stash entriesRemoves every entry at once; the manual warns they may be impossible to recover.

Tags and notes 8

CommandWhat it does
git tagList tagsPrints all tag names; add -l with a pattern to filter them.
git tag TAGNAMECreate a lightweight tagWithout -a, -s or -u it only creates a name pointing at HEAD or at a commit you add.
git tag -a TAGNAMECreate an annotated tagMakes a full tag object with tagger, date and message; an editor opens unless -m is given.
git tag -d TAGNAMEDelete a tagDeletes the named local tags; several names can be given at once.
git tag -l PATTERNList tags matching a patternTreats the pattern as a shell wildcard and prints only the matching tag names.
git verify-tag TAGCheck tag signaturesValidates the signature that git tag put on each tag object listed.
git verify-commit COMMITCheck commit signaturesValidates the signature that git commit -S put on the commits you name.
git notesList commit notesNotes attach extra text to a commit without changing the commit itself.

Rebasing and cherry-picking 14

CommandWhat it does
git rebaseRebase onto the upstream branchWith no arguments it replays your commits on the configured upstream of the current branch.
git rebase masterRebase onto another branchReapplies the commits of the checked-out branch on top of the tip of master.
git rebase -i HEAD~5Edit the last five commitsOpens the todo list for those commits so you can reorder, squash, reword or drop them.
git rebase --onto master next topicMove a branch to a new baseReplays the commits of topic that are not in next onto master.
git rebase --continueContinue after conflictsResumes the rebase once the conflicted files are fixed and marked resolved with git add.
git rebase --abortCancel a rebaseEnds the operation and puts the branch back where it was before the rebase.
git rebase --autosquashFold fixup commits while rebasingMoves commits whose message starts with fixup! or squash! next to their target and combines them.
git commit --fixup COMMITCommit a fix for an earlier commitMakes a fixup! commit that a later rebase with --autosquash folds into the named commit.
git cherry-pick COMMITCopy a commit onto this branchApplies the change that commit introduced and records it as a new commit here.
git cherry-pick --continueContinue a cherry-pickCarries on with the sequence after the conflicts have been resolved.
git cherry-pick --abortCancel a cherry-pickGives up on the sequence and restores the state from before it started.
git history reword COMMITReword an older commitExperimental command: opens an editor on that commit's message and changes nothing else in it.
git filter-branchRewrite history with filtersRewrites whole branches through custom filters; the manual warns of pitfalls and recommends git filter-repo.
git replace OBJECT REPLACEMENTSubstitute one object for anotherCreates a ref under refs/replace/ so that Git reads the replacement wherever the original is used.

Worktrees, submodules and sparse checkout 10

CommandWhat it does
git worktree add PATHAdd a working treeCreates a second checkout at that path on a new branch named after the last path component.
git worktree listList working treesShows each working tree with its path, checked-out commit and branch; the main one comes first.
git worktree remove WORKTREERemove a working treeWorks only on a clean linked working tree unless -f is added; the main one cannot be removed.
git submoduleShow submodule statusCalled without a subcommand it reports the state of each submodule.
git submodule add REPOSITORY PATHAdd a submoduleClones the repository at that path and stages the new submodule for the next commit of the superproject.
git submodule updateCheck out submodule commitsClones missing submodules and checks out the commit the superproject records for each.
git submodule update --init --recursiveFetch all nested submodulesInitialises and updates every submodule, including those inside other submodules.
git sparse-checkout set MY/DIR1 SUB/DIR2Limit checkout to directoriesKeeps the files under the listed directories, plus those directly in their parent folders and at top level.
git sparse-checkout disableTurn sparse checkout offBrings every tracked file back into the working directory.
git backfillDownload missing blobsIn a blobless partial clone, fetches the missing file contents in batches ahead of time.

Patches and email 8

CommandWhat it does
git format-patch originExport commits as patch filesWrites one mail-formatted file per commit that is on your branch but not on origin.
git amApply patches from a mailboxReads mbox files, or standard input, and turns each message into a commit.
git am --continueContinue applying patchesCarries on after a failed patch has been fixed up by hand and staged.
git apply PATCHApply a patch fileChanges working tree files only and makes no commit; also works outside a repository.
git send-email FILEEmail patch filesSends each patch as a mail; a directory or a revision list can be given in place of files.
git imap-sendUpload patches to an IMAP folderReads a mailbox made by git format-patch from standard input and stores it in your drafts folder.
git request-pull START URLWrite a pull request summaryPrints a summary of your changes since the start commit and where they can be pulled from.
git quiltimportApply a quilt patch seriesApplies the series to the current branch, keeping patch order, boundaries and descriptions.

Maintenance and repair 14

CommandWhat it does
git gcClean up and optimiseCompresses file revisions and removes unreachable objects to save disk space and speed things up.
git maintenance runRun maintenance tasks nowRuns the enabled maintenance tasks once; by default that is only gc.
git fsckCheck repository integrityChecks that every object is valid and connected, and reports dangling or corrupt ones.
git pruneDelete unreachable objectsRemoves loose objects that no ref can reach; normally git gc runs it for you.
git repackPack loose objectsCombines objects not yet in a pack into one; with -a everything is rebuilt into a single pack.
git pack-refsPack branch and tag refsStores many refs in the single file packed-refs rather than one file per ref.
git count-objectsCount loose objectsReports how many unpacked objects exist and the disk space they take; -v gives more detail.
git refs listList referencesAlias of git for-each-ref: lists refs with filtering, sorting and custom formats.
git archive -o latest.zip HEADExport a commit as an archiveWrites the files of the latest commit to latest.zip; the format follows the file extension.
git bundle create file.bundle masterPack history into one fileWrites master and its history to a file that another machine can clone or fetch from offline.
git fast-exportDump history as a streamWrites revisions in the text format that git fast-import reads back.
git fast-importImport a history streamReads commands and data from standard input and writes packfiles; normally driven by an importer.
git bugreportCreate a bug report fileCollects system and repository details plus a questionnaire into one text file you can send to the Git list.
git diagnoseCollect diagnostics as a zipPackages details of the machine, the Git client and the repository state into a zip archive.

Other version control systems 6

CommandWhat it does
git svn clone http://svn.example.com/project/trunkClone a Subversion repositoryCreates a Git repository tracking that Subversion path; later changes flow both ways.
git p4 clone P4-DEPOT-PATHClone a Perforce depotCreates a Git repository from one or more p4 depot paths.
git cvsimportImport a CVS repositoryNeeds cvsps version 2, which the manual calls deprecated; it suggests cvs2git for one-off imports.
git cvsexportcommit COMMIT-IDExport a commit to CVSApplies one Git commit to a CVS checkout and does not commit there by default.
git cvsserverServe a repository to CVS clientsEmulation layer that lets CVS clients work against a Git repository; not every CVS method is implemented.
git archimportImport from GNU ArchImports one or more Arch repositories and marks merges where it can find the source branch.

Notes

The 80% loop

Daily git is five commands: git status → git add PATHSPEC → git commit → git pull → git push. The habit that prevents most accidents is running git status before and after anything else — it tells you the branch, what's staged, and what would be committed. git add . stages everything under the current directory; prefer naming files (git add PATHSPEC) when a change set mixes concerns, and let git log --oneline be the sanity check that history looks the way you think it does.

Branching: cheap to make, cheap to delete

git checkout -b NEW-BRANCH creates and switches in one step (newer git also offers git switch -c NEW-BRANCH). Merging brings a branch's work in with history intact; git rebase replays your commits on top of another branch for a linear history — the working rule is to rebase only commits that haven't been pushed anywhere shared, because rebase rewrites them. git branch -d BRANCH-NAME deletes a merged branch and refuses an unmerged one; that refusal is a feature, not an obstacle.

The undo toolbox, sorted by blast radius

Gentlest first: git stash shelves uncommitted work and git stash pop restores it — ideal for “wrong branch” moments. git restore --staged PATHSPEC unstages without touching the file's contents. git cherry-pick COMMIT copies a single commit onto the current branch. At the destructive end, git reset --hard HEAD^ deletes the last commit and its changes from the working tree — use it only when you truly want the work gone, and remember committed-then-reset work is recoverable via git reflog for a grace period.

Questions

What is the difference between git fetch and git pull?

fetch downloads remote changes without touching your working branch; pull runs fetch and then integrates the upstream branch into the current one. By default pull only fast-forwards: git pull --rebase or git pull --no-rebase picks a rebase or a merge when the branches have diverged. Fetch first when you want to inspect before integrating.

When should I rebase instead of merge in git?

Rebase local, unpushed commits to keep history linear; merge anything already shared. Rewriting pushed commits forces everyone else to untangle it.

What does git stash actually store?

Uncommitted tracked changes (staged and unstaged). git stash pop restores the most recent stash and drops it; git stash apply restores but keeps it in the stash list.

How do I copy one commit to another branch?

git cherry-pick <hash> from the target branch. It creates a new commit with the same changes — the original stays where it was.

Why won't git branch -d delete my branch?

-d refuses if the branch isn't merged, protecting unmerged work. If you're certain, -D force-deletes.

How do I get stashed changes back in Git?

Run git stash pop. It applies the most recent stash to the working tree and removes that entry from the stash list. git stash apply does the same but keeps the entry, which is the safer choice when the same changes are needed on more than one branch.

git stash list shows every entry, the newest as stash@{0}. Name an entry to restore an older one, for example git stash pop stash@{1}. If the pop stops on a conflict the entry is not removed: resolve the conflict, then delete it with git stash drop.

How do I undo the last Git commit?

Run git reset HEAD~1 to remove the last commit and keep its changes as unstaged edits in the working tree. git reset --soft HEAD~1 keeps them staged instead. git reset --hard HEAD~1 throws them away, together with any other uncommitted changes to tracked files.

If the commit has already been pushed to a shared branch, leave history alone: git revert HEAD adds a new commit that reverses it. After a reset made by mistake, git reflog shows where HEAD pointed before, and resetting to that entry brings the commit back.

Sources and checks

80 more source pages

Every row on this page was matched to a line in the documentation above on . A binding that could not be found there is not listed.

Found a wrong or missing key? Tell us and it gets checked against the source. How we verify describes the process and its limits.