Create an archive of files from a named tree
Creates an archive of the specified format containing the tree structure for the named tree, and writes it out to the standard output. If <prefix> is specified it is prepended to the filenames in the archive
git archive behaves differently when given a tree ID versus when given a commit ID or tag ID. In the first case the current time is used as the modification time of each file in the archive. In the latter case the commit time as recorded in the referenced commit object is used instead. Additionally the commit ID is stored in a global extended pax header if the tar format is used; it can be extracted using git get-tar-commit-id. In ZIP files it is stored as a file comment
git archive [--format=<fmt>] [--list] [--prefix=<prefix>/] [<extra>] [-o <file> | --output=<file>] [--worktree-attributes] [--remote=<repo> [--exec=<git-upload-archive>]] <tree-ish> [<path>...]
--format=<fmt> # Format of the resulting archive: tar or zip. If this option is not given, and the output file is specified, the format is inferred from the filename if possible (e.g. writing to "foo.zip" makes the output to be in the zip format). Otherwise the output format is tar
-l, --list # Show all available formats
-v, --verbose # Report progress to stderr
--prefix=<prefix>/ # Prepend <prefix>/ to each filename in the archive
-o <file>, --output=<file> # Write the archive to <file> instead of stdout
--worktree-attributes # Look for attributes in .gitattributes files in the working tree as well (see the section called “ATTRIBUTES”)
<extra> # This can be any options that the archiver backend understands. See next section
--remote=<repo> # Instead of making a tar archive from the local repository, retrieve a tar archive from a remote repository. Note that the remote repository may place restrictions on which sha1 expressions may be allowed in <tree-ish>. See git-upload-archive(1) for details
--exec=<git-upload-archive> # Used with --remote to specify the path to the git-upload-archive on the remote side
<tree-ish> # The tree or commit to produce an archive for
<path> # Without an optional path parameter, all files and subdirectories of the current working directory are included in the archive. If one or more paths are specified, only these are included
EXAMPLES
# Create a tar archive that contains the contents of the latest commit on the current branch, and extract it in the /var/tmp/junk directory
git archive --format=tar --prefix=junk/ HEAD | (cd /var/tmp/ && tar xf -)
# Create a compressed tarball for v1.4.0 release
git archive --format=tar --prefix=git-1.4.0/ v1.4.0 | gzip >git-1.4.0.tar.gz
# Same as above, but using the builtin tar.gz handling
git archive --format=tar.gz --prefix=git-1.4.0/ v1.4.0 >git-1.4.0.tar.gz
# Same as above, but the format is inferred from the output file
git archive --prefix=git-1.4.0/ -o git-1.4.0.tar.gz v1.4.0
# Create a compressed tarball for v1.4.0 release, but without a global extended pax header
git archive --format=tar --prefix=git-1.4.0/ v1.4.0^{tree} | gzip >git-1.4.0.tar.gz
# Put everything in the current head’s Documentation/ directory into git-1.4.0-docs.zip, with the prefix git-docs/
git archive --format=zip --prefix=git-docs/ HEAD:Documentation/ > git-1.4.0-docs.zip
# Create a Zip archive that contains the contents of the latest commit on the current branch. Note that the output format is inferred by the extension of the output file
git archive -o latest.zip HEAD
git config tar.tar.xz.command "xz -c"
# Configure a "tar.xz" format for making LZMA-compressed tarfiles. You can use it specifying --format=tar.xz, or by creating an output file like -o foo.tar.xz
TRICKS
Un zip avec uniquement vos fichiers et surtout l’arborescence des fichiers qui va avec
git archive -o delta.zip develop $(git diff --name-only V1.0.0^)
Inconvénient de cette méthodes, les fichiers supprimé ne seront pas supprimé et la commande ci-dessus va planter.
Il faut donc ajouter un filtrer sur les fichiers. Exemple pour ne prendre en compte que les fichier Ajouter, Modifier, Renommer, Changer)
git archive -o delta.zip develop $(git diff --name-only --diff-filter=ACMRT V1.0.0^)
Reapply commits on top of another base tip
If <branch> is specified, git rebase will perform an automatic git switch <branch> before doing anything else. Otherwise it remains on the current branch
A---B---C topic
/
D---E---F---G master
git checkout topic && git rebase master
git rebase master topic
# rebase (from) master (for) topic
A'--B'--C' topic
/
D---E---F---G master
----------------------------------------------------
o---o---o---o---o master
\
o---o---o---o---o next
\
o---o---o topic
git rebase --onto master next topic
# rebase (onto) master (from) next (for) topic
o---o---o---o---o master
| \
| o'--o'--o' topic
\
o---o---o---o---o next
git rebase [-i | --interactive] [<options>] [--exec <cmd>] [--onto <newbase> | --keep-base] [<upstream> [<branch>]]
git rebase [-i | --interactive] [<options>] [--exec <cmd>] [--onto <newbase>] --root [<branch>]
git rebase (--continue | --skip | --abort | --quit | --edit-todo | --show-current-patch)
--onto <newbase> # Starting point at which to create the new commits. If the --onto option is not specified, the starting point is <upstream>. May be any valid commit, and not just an existing branch name
--keep-base # Set the starting point at which to create the new commits to the merge base of <upstream> <branch>. Running git rebase --keep-base <upstream> <branch> is equivalent to running git rebase --onto <upstream>... <upstream>
<upstream> # Upstream branch to compare against. May be any valid commit, not just an existing branch name. Defaults to the configured upstream for the current branch
<branch> # Working branch; defaults to HEAD
--continue # Restart the rebasing process after having resolved a merge conflict
--abort # Abort the rebase operation and reset HEAD to the original branch. If <branch> was provided when the rebase operation was started, then HEAD will be reset to <branch>. Otherwise HEAD will be reset to where it was when the rebase operation was started
--quit # Abort the rebase operation but HEAD is not reset back to the original branch. The index and working tree are also left unchanged as a result
--keep-empty # Keep the commits that do not change anything from its parents in the result
--allow-empty-message # By default, rebasing commits with an empty message will fail. This option overrides that behavior, allowing commits with empty messages to be rebased
--skip # Restart the rebasing process by skipping the current patch
--edit-todo # Edit the todo list during an interactive rebase
--show-current-patch # Show the current patch in an interactive rebase or when rebase is stopped because of conflicts. This is the equivalent of git show REBASE_HEAD
-m, --merge # Use merging strategies to rebase. When the recursive (default) merge strategy is used, this allows rebase to be aware of renames on the upstream side
-s <strategy>, --strategy=<strategy> # Use the given merge strategy. If there is no -s option git merge-recursive is used instead. This implies --merge
-X <strategy-option>, --strategy-option=<strategy-option> # Pass the <strategy-option> through to the merge strategy. This implies --merge and, if no strategy has been specified, -s recursive. Note the reversal of ours and theirs as noted above for the -m option
--rerere-autoupdate, --no-rerere-autoupdate # Allow the rerere mechanism to update the index with the result of auto-conflict resolution if possible
-S[<keyid>], --gpg-sign[=<keyid>] # GPG-sign commits. The keyid argument is optional and defaults to the committer identity; if specified, it must be stuck to the option without a space
-q, --quiet # Be quiet. Implies --no-stat
-v, --verbose # Be verbose. Implies --stat
--stat # Show a diffstat of what changed upstream since the last rebase. The diffstat is also controlled by the configuration option rebase.stat
-n, --no-stat # Do not show a diffstat as part of the rebase process
--no-verify # This option bypasses the pre-rebase hook. See also githooks(5)
--verify # Allows the pre-rebase hook to run, which is the default. This option can be used to override --no-verify. See also githooks(5)
-C<n> # Ensure at least <n> lines of surrounding context match before and after each change. When fewer lines of surrounding context exist they all must match. By default no context is ever ignored
--no-ff, --force-rebase, -f # Individually replay all rebased commits instead of fast-forwarding over the unchanged ones. This ensures that the entire history of the rebased branch is composed of new commits
--fork-point, --no-fork-point # Use reflog to find a better common ancestor between <upstream> and <branch> when calculating which commits have been introduced by <branch>
--ignore-whitespace, --whitespace=<option> # These flag are passed to the git apply program (see git-apply(1)) that applies the patch
--committer-date-is-author-date, --ignore-date # These flags are passed to git am to easily change the dates of the rebased commits (see git-am(1))
--signoff # Add a Signed-off-by: trailer to all the rebased commits. Note that if --interactive is given then only commits marked to be picked, edited or reworded will have the trailer added
-i, --interactive # Make a list of the commits which are about to be rebased. Let the user edit that list before rebasing. This mode can also be used to split commits (see SPLITTING COMMITS below)
-r, --rebase-merges[=(rebase-cousins|no-rebase-cousins)] # By default, a rebase will simply drop merge commits from the todo list, and put the rebased commits into a single, linear branch. With --rebase-merges, the rebase will instead try to preserve the branching structure within the commits that are to be rebased, by recreating the merge commits
-p, --preserve-merges # [DEPRECATED: use --rebase-merges instead] Recreate merge commits instead of flattening the history by replaying commits a merge commit introduces. Merge conflict resolutions or manual amendments to merge commits are not preserved
-x <cmd>, --exec <cmd> # Append "exec <cmd>" after each line creating a commit in the final history. <cmd> will be interpreted as one or more shell commands. Any command that fails will interrupt the rebase, with exit code 1
--root # Rebase all commits reachable from <branch>, instead of limiting them with an <upstream>. This allows you to rebase the root commit(s) on a branch
--autosquash, --no-autosquash # When the commit log message begins with "squash! ..." (or "fixup! ..."), and there is already a commit in the todo list that matches the same ..., automatically modify the todo list of rebase -i so that the commit marked for squashing comes right after the commit to be modified, and change the action of the moved commit from pick to squash (or fixup)
--autostash, --no-autostash # Automatically create a temporary stash entry before the operation begins, and apply it after the operation ends. This means that you can run rebase on a dirty worktree. However, use with care: the final stash application after a # successful rebase might result in non-trivial conflicts
--reschedule-failed-exec, --no-reschedule-failed-exec
Automatically reschedule exec commands that failed. This only makes sense in interactive mode (or when an --exec option was provided)
INCOMPATIBLE OPTIONS
The following options:
--committer-date-is-author-date
--ignore-date
--whitespace
--ignore-whitespace
-C
are incompatible with the following options:
--merge
--strategy
--strategy-option
--allow-empty-message
--[no-]autosquash
--rebase-merges
--preserve-merges
--interactive
--exec
--keep-empty
--edit-todo
--root when used in combination with --onto
In addition, the following pairs of options are incompatible:
--preserve-merges and --interactive
--preserve-merges and --signoff
--preserve-merges and --rebase-merges
--keep-base and --onto
--keep-base and --root
Switch branches
Switch to a specified branch. The working tree and the index are updated to match the branch. All new commits will be added to the tip of this branch
Optionally a new branch could be created with either -c, -C, automatically from a remote branch of same name (see --guess), or detach the working tree from any branch with --detach, along with switching
Switching branches does not require a clean index and working tree (i.e. no differences compared to HEAD). The operation is aborted however if the operation leads to loss of local changes, unless told otherwise with --discard-changes or --merge
git switch [<options>] [--no-guess] <branch>
git switch [<options>] --detach [<start-point>]
git switch [<options>] (-c|-C) <new-branch> [<start-point>]
git switch [<options>] --orphan <new-branch>
<branch> # Branch to switch to
<new-branch> # Name for the new branch
<start-point> # The starting point for the new branch. Specifying a <start-point> allows you to create a branch based on some other point in history than where HEAD currently points. (Or, in the case of --detach, allows you to inspect and detach from some other point.)
-c <new-branch>, --create <new-branch> # Create a new branch named <new-branch> starting at <start-point> before switching to the branch
-C <new-branch>, --force-create <new-branch> # Similar to --create except that if <new-branch> already exists, it will be reset to <start-point>
-d, --detach # Switch to a commit for inspection and discardable experiments
--guess, --no-guess # If <branch> is not found but there does exist a tracking branch in exactly one remote (call it <remote>) with a matching name, treat as equivalent to
git switch -c <branch> --track <remote>/<branch>
-f, --force # An alias for --discard-changes
--discard-changes # Proceed even if the index or the working tree differs from HEAD. Both the index and working tree are restored to match the switching target
-m, --merge # If you have local modifications to one or more files that are different between the current branch and the branch to which you are switching, the command refuses to switch branches in order to preserve your modifications in context
--conflict=<style> # The same as --merge option above, but changes the way the conflicting hunks are presented, overriding the merge.conflictStyle configuration variable
--progress, --no-progress # Progress status is reported on the standard error stream by default when it is attached to a terminal, unless --quiet is specified. This flag enables progress reporting even if not attached to a terminal, regardless of --quiet
-t, --track # When creating a new branch, set up "upstream" configuration. -c is implied. See --track in git-branch(1) for details
--no-track # Do not set up "upstream" configuration, even if the branch.autoSetupMerge configuration variable is true
--orphan <new-branch> # Create a new orphan branch, named <new-branch>. All tracked files are removed
--ignore-other-worktrees # git switch refuses when the wanted ref is already checked out by another worktree. This option makes it check the ref out anyway. In other words, the ref can be held by more than one worktree
--recurse-submodules, --no-recurse-submodules # Using --recurse-submodules will update the content of all initialized submodules according to the commit recorded in the superproject
EXAMPLES
The following command switches to the "master" branch:
git switch master
After working in the wrong branch, switching to the correct branch would be done using:
git switch mytopic
However, your "wrong" branch and correct "mytopic" branch may differ in files that you have modified locally, in which case the above switch would fail like this:
git switch mytopic
error: You have local changes to 'frotz'; not switching branches
You can give the -m flag to the command, which would try a three-way merge:
git switch -m mytopic
Auto-merging frotz
After this three-way merge, the local modifications are not registered in your index file, so git diff would show you what changes you made since the tip of the new branch
To switch back to the previous branch before we switched to mytopic (i.e. "master" branch):
git switch -
You can grow a new branch from any commit. For example, switch to "HEAD~3" and create branch "fixup":
git switch -c fixup HEAD~3
Switched to a new branch 'fixup'
If you want to start a new branch from a remote branch of the same name:
git switch new-topic
Branch 'new-topic' set up to track remote branch 'new-topic' from 'origin'
Switched to a new branch 'new-topic'
To check out commit HEAD~3 for temporary inspection or experiment without creating a new branch:
git switch --detach HEAD~3
HEAD is now at 9fc9555312 Merge branch 'cc/shared-index-permbits'
git-restore - Restore working tree files
MRestore specified paths in the working tree with some contents from a restore source. If a path is tracked but does not exist in the restore source, it will be removed to match the source
The command can also be used to restore the content in the index with --staged, or restore both the working tree and the index with --staged --worktree
By default, the restore sources for working tree and the index are the index and HEAD respectively. --source could be used to specify a commit as the restore source
git restore [<options>] [--source=<tree>] [--staged] [--worktree] [--] <pathspec>...
git restore [<options>] [--source=<tree>] [--staged] [--worktree] --pathspec-from-file=<file> [--pathspec-file-nul]
git restore (-p|--patch) [<options>] [--source=<tree>] [--staged] [--worktree] [--] [<pathspec>...]
-s <tree>, --source=<tree> # Restore the working tree files with the content from the given tree. It is common to specify the source tree by naming a commit, branch or tag associated with it.
-p, --patch # Interactively select hunks in the difference between the restore source and the restore location. See the “Interactive Mode” section of git-add(1) to learn how to operate the --patch mode.
-W, --worktree, -S, --staged # Specify the restore location. If neither option is specified, by default the working tree is restored. Specifying --staged will only restore the index. Specifying both restores both.
-q, --quiet # Quiet, suppress feedback messages. Implies --no-progress.
--progress, --no-progress # Progress status is reported on the standard error stream by default when it is attached to a terminal, unless --quiet is specified. This flag enables progress reporting even if not attached to a terminal, regardless of --quiet.
--ours, --theirs # When restoring files in the working tree from the index, use stage #2 (ours) or #3 (theirs) for unmerged paths.
-m, --merge # When restoring files on the working tree from the index, recreate the conflicted merge in the unmerged paths.
--conflict=<style> # The same as --merge option above, but changes the way the conflicting hunks are presented, overriding the merge.conflictStyle configuration variable. Possible values are "merge" (default) and "diff3" (in addition to what is shown by # "merge" style, shows the original contents).
--ignore-unmerged # When restoring files on the working tree from the index, do not abort the operation if there are unmerged entries and neither --ours, --theirs, --merge or --conflict is specified. Unmerged paths on the working tree are left alone.
--ignore-skip-worktree-bits # In sparse checkout mode, by default is to only update entries matched by <pathspec> and sparse patterns in $GIT_DIR/info/sparse-checkout. This option ignores the sparse patterns and unconditionally restores any files in <pathspec>.
--overlay, --no-overlay # In overlay mode, the command never removes files when restoring. In no-overlay mode, tracked files that do not appear in the --source tree are removed, to make them match <tree> exactly. The default is no-overlay mode.
--pathspec-from-file=<file> # Pathspec is passed in <file> instead of commandline args. If <file> is exactly - then standard input is used. Pathspec elements are separated by LF or CR/LF. Pathspec elements can be quoted as explained for the configuration variable core.quotePath (see git-config(1)). See also --pathspec-file-nul and global --literal-pathspecs.
--pathspec-file-nul # Only meaningful with --pathspec-from-file. Pathspec elements are separated with NUL character and all other characters are taken literally (including newlines and quotes).
-- # Do not interpret any more arguments as options.
<pathspec>... # Limits the paths affected by the operation.
EXAMPLES
The following sequence switches to the master branch, reverts the Makefile to two revisions back, deletes hello.c by mistake, and gets it back from the index
git switch master
git restore --source master~2 Makefile # take a file out of another commit
rm -f hello.c
git restore hello.c # restore hello.c from the index
If you want to restore all C source files to match the version in the index, you can say
git restore '*.c'
Note the quotes around *.c. The file hello.c will also be restored, even though it is no longer in the working tree, because the file globbing is used to match entries in the index (not in the working tree by the shell).
To restore all files in the current directory
git restore .
or to restore all working tree files with top pathspec magic (see gitglossary(7))
git restore :/
To restore a file in the index to match the version in HEAD (this is the same as using git-reset(1))
git restore --staged hello.c
or you can restore both the index and the working tree (this the same as using git-checkout(1))
git restore --source=HEAD --staged --worktree hello.c
or the short form which is more practical but less readable:
git restore -s@ -SW hello.c
https://www.atlassian.com/fr/git/tutorials
https://git-scm.com/docs
TOC
chapter | |
---|---|
REFERENCE | USED |
- URL | - ADD |
- VALUES | - ARCHIVE |
GITHUB | - BRANCH |
GPG | - CHECKOUT |
GITIGNORE | - CLONE |
TRICKS | - COMMIT |
- CONFIG | |
- LOG | |
- MERGE | |
- PULL | |
- PUSH | |
- REMOTE | |
- RESET | |
- SUBMODULE | |
- SWITCH | |
- TAG |
REFERENCE
URL
https://<fqdn>/<user>/<project> # https://github.com/aguytech/Shaarli
git@<fqdn>:<user>/<project>.git # git@github.com:aguytech/Shaarli.git
VALUES
git rev-parse --symbolic-full-name --abbrev-ref @{upstream} # print value for upstream
git rev-parse --symbolic-full-name --abbrev-ref @{push} # print value for push
git for-each-ref --format='%(refname:short) <- %(upstream:short)' refs/heads # show all upstream
git for-each-ref --format='%(upstream:short)' "$(git symbolic-ref -q HEAD)" # idem
git for-each-ref --format='%(refname:short) <- %(push:short)' refs/heads # show all upstream
git for-each-ref --format='%(push:short)' "$(git symbolic-ref -q HEAD)" # idem
USED
ADD
git add -i / --interactive # add with interactively mode
git add -u / --update # Update the index for already referred files (just where it already has an entry matching <pathspec>
gi add -A / --all / --no-ignore-removal # add all files
ARCHIVE
git archive -l # list available formats
git archive --format tar.gz -9 -o "$(git br --show-current).$(date +%s).tar.gz" <branch> # create an archive from local <branch> with best compression -9 & in format tar.gz
BRANCH
https://stackoverflow.com/questions/11266478/git-add-remote-branch
list
git branch / git br # print list of local branches
git br -v # print informations about local branches
git br -vv # print full information about local branches
git branch -a -vv # print full information about all branches
git br --show-current # show name of current branch
git br -r # print list of remote branches for all repositories
git br -rlv <remote>/<pattern> # list remote branches for <remote> repository & with name matched <pattern>
create/delete
git br <branch> # create a local branch
git br <branch> <remote>/<remote_branch> # create local branch from remote
git br -u <remote>/<remote_branch> <branch> # attach a local branch to remote existing one
git br --set-upstream-to=<remote>/<remote_branch> <branch> # idem
# Equal to: git checkout <branch> && git push --set-upstream <remote> <branch>
git br -m <branch> <new_branch># rename local branch && 'git push'
git br -d <branch> # delete local branch
git br -rd <remote>/<branch> # delete remote branch
CHECKOUT
git co -b <branch> # create a branch from HEAD and switch to it
git co -t <repo>/<branch> -b <branch> # create a local branch from <repo>/<branch>
git co --orphan=<branch> # create an orphan branch (whithout history)
git co --orphan=<branch> # create an orphan branch (whithout history)
git co --detach -b <branch> # check out a commit for inspection and discardable experiments
CLONE
git clone <url> # clone a repository
git clone <url> <alias> # clone a repository & give it an alias
git clone -b <branch> <url> # clone only one branch from repository
git clone -b v0.11-snippets --single-branch --no-tags git@github.com:aguytech/Shaarli.git shaarli-snippets # clone from a repository a single branch
COMMIT
# amend
git commit --amend --no-edit # amends a commit without changing its commit message
git commit --amend -m "message" # amends a commit with a new message
CONFIG
# amend
git config <variable> # show variable and his value
git config --global core.editor vim # set selected editor
git config -l # list all config variables
git config -l --show-origin # list all config variables with their origins
git config -l --name-only # list all names of system config variables
git config -l --local # list all config variables defined for user
git config -l --global # list all global config variables for global users
git config -l --system # list all system config variables for system
LOG
git log # show logs
git log -n3 <repo>/<branch> # show only last 23 lines of logs
git log --pretty=format:'%h' -n1 <repo>/<branch> # show short sha of last commit
git log --name-only # with file names
git log --name-status # with file names with its status
git log --stat # with file names with its statisticals
git reflog # show logs with a reference (sha) view
MERGE
git merge -m "message" <branch> # merge branch with actual one with a message to committing
git merge --allow-unrelated-histories <branch> # allows to merge branch with no common history
PULL
If you tried a pull which resulted in complex conflicts and would want to start over, you can recover with git reset
git pull # Update actual local branch from current remote
git pull <remote> # Update actual local branch from a selected remote
git pull <remote> <branch> # Merge into the current branch the remote branch
<=>
git fetch origin
git merge origin/next
git pull --rebase # pull automatically last modifications on remote (with fetch + merge) & put your validation on head directly
pull all submodules
git submodule foreach git pull
git submodule foreach git pull origin master
git submodule foreach 'git pull origin master || true' # for some submodules without updates"
PUSH
git push -u <remote> <branch> # set upstream for actual local branch & push it to remote (create one if needed), while you created a local branch to local and you want to push to another repository !
git push --tags # push tags also
git push -d <remote> <branch> # delete remote branch
REMOTE
git remote rename <name> <new_name> # rename a remote source
git remote add <name> <url> # add a remote source to repository
git remote add -t <branch> <name> <url> # add only a branch from a repository like source
git remote remove <name> # remove/delete a remote source to repository
RESET
git reset --merge # resets the index and updates the files in the working tree that are different between <commit> and HEAD
git reset --hard <commit_sha> # reset branch to commit_sha, 'git reflog' is an better way to find commit_sha
git reset --hard HEAD~1
SWITCH
TAG
git tag -l # List all tags
git tag -a -m "message" # Defines an unsigned, annoted tag
git tag -s "tag" -m "message" # Creates a signed tag with message (define the default key with git config --global user.signingkey before)
git tag -s <tag> -u <keyid> -m <message> # Creates a signed tag with a specified key user
git tag -d <tag> # Delete existing tags with the given names
git tag -v <tag> # Verify the GPG signature of the given tag names
git push --delete origin <tag> # delete tag in origin
# rename tag
git tag new old
git tag -d old
git push origin new :old
git pull --prune --tags # for coworkers
SUBMODULE
git submodule add <url> # add submodule to actual repository
GITHUB
create a local git repository and publish it to github
touch README.md
git init
git add *
git status
git commit -m "First commit"
git remote add origin <url>
git push -u origin master
GPG
https://kamarada.github.io/en/2019/07/14/using-git-with-ssh-keys/
GITHUB
-
import public to github
-
test
ssh -T git@github.com # test ssh connection ssh -T -p 443 git@ssh.github.com # test ssh connection over https
-
set the default key
git config --global user.signingkey <keyid>
change remote url for remote existing repository
git remote -v # print https://github.com/user/project
git remote set-url origin git@github.com:user/project.git # change the connection url to use ssh
git remote -v # print git@github.com:user/project.git
delete tags
git tag -d [tag];
git push origin :[tag]
git tag -d [tag]
git push origin :refs/tags/[tag]
GITIGNORE
https://www.atlassian.com/git/tutorials/saving-changes/gitignore
pattern
**/path # match directories anywhere in the repository, relative definition
*.pattern # matches zero or more characters
!pattern # mark to a pattern negates it
/pattern # matches files only in the repository root
path/ # appending a slash indicates the pattern is a directory
debug?.log # a question mark matches exactly one character
debug[0-9].log # Square brackets matches a single character from a specified range like [01] [a-z] [A-Z]
debug[!01].log # an exclamation mark matches any character except one from the specified set
logs/**/debug.log # a double asterisk matches zero or more directories like logs/*day/debug.log
example
*.ba[kt]
*~
!myfile.a # include file in repo
tmp/ # exclude all files in directory tmp
head/**/*.tmp # exclude all files *.tmp in subdirectory of head
TRICKS
create orphan repo from another
Create origin to remote server
repo_local="shaarli-snippets"
tmp_branch="dev"
origin="github"
url_origin="git@github.com:aguytech/Shaarli-snippets.git"
upstream="shaarli"
url_upstream="git@github.com:aguytech/Shaarli.git"
upstream_branch="v0.11-snippets" # remote branch to track
mkdir -p "$repo_local"
cd "$repo_local"
git init
# remote
git remote add "$origin" "$url_origin"
git remote add -t "$upstream_branch" "$upstream" "$url_upstream"
git remote -v
git config --get-regexp '^remote'
# upstream
git fetch "$upstream"
git co --orphan="$tmp_branch" "$upstream"/"$upstream_branch"
git st
git ci -m "Initialize branch from $upstream/$upstream_branch $(git log --pretty=format:'%h' -n 1 "$upstream"/"$upstream_branch")"
# origin
git push --set-upstream "$origin" "$tmp_branch"
git co -b master
git push --set-upstream "$origin" master
git br -vv
git br -rlv github/*
# archive
git archive --format tar.gz -9 -o "master.$(date +%s).tar.gz" master
add a submodule
git submodule add $url
git diff --cached $submodule
git diff --cached --submodule
git commit -m "Add $submodule module"
clone with submodules
git clone --recurse-submodules
GIT URLS
In general, URLs contain information about the transport protocol, the address of the remote server, and the path to the repository. Depending on the
transport protocol, some of this information may be absent.
Git supports ssh, git, http, and https protocols (in addition, ftp, and ftps can be used for fetching, but this is inefficient and deprecated; do not use
it).
The native transport (i.e. git:// URL) does no authentication and should be used with caution on unsecured networks.
The following syntaxes may be used with them:
- ssh://[user@]host.xz[:port]/path/to/repo.git/
- git://host.xz[:port]/path/to/repo.git/
- http[s]://host.xz[:port]/path/to/repo.git/
- ftp[s]://host.xz[:port]/path/to/repo.git/
An alternative scp-like syntax may also be used with the ssh protocol:
- [user@]host.xz:path/to/repo.git/
This syntax is only recognized if there are no slashes before the first colon. This helps differentiate a local path that contains a colon. For example the
local path foo:bar could be specified as an absolute path or ./foo:bar to avoid being misinterpreted as an ssh url.
The ssh and git protocols additionally support ~username expansion:
- ssh://[user@]host.xz[:port]/~[user]/path/to/repo.git/
- git://host.xz[:port]/~[user]/path/to/repo.git/
- [user@]host.xz:/~[user]/path/to/repo.git/
For local repositories, also supported by Git natively, the following syntaxes may be used:
- /path/to/repo.git/
- file:///path/to/repo.git/
These two syntaxes are mostly equivalent, except when cloning, when the former implies --local option
git clone, git fetch and git pull, but not git push, will also accept a suitable bundle file
When Git doesn’t know how to handle a certain transport protocol, it attempts to use the remote-<transport> remote helper, if one exists. To explicitly
request a remote helper, the following syntax may be used:
- <transport>::<address>
where <address> may be a path, a server and path, or an arbitrary URL-like string recognized by the specific remote helper being invoked
If there are a large number of similarly-named remote repositories and you want to use a different format for them (such that the URLs you use will be rewritten into URLs that work), you can create a configuration section of the form:
[url "<actual url base>"]
insteadOf = <other url base>
For example, with this:
[url "git://git.host.xz/"]
insteadOf = host.xz:/path/to/
insteadOf = work:
a URL like "work:repo.git" or like "host.xz:/path/to/repo.git" will be rewritten in any context that takes a URL to be "git://git.host.xz/repo.git".
If you want to rewrite URLs for push only, you can create a configuration section of the form:
[url "<actual url base>"]
pushInsteadOf = <other url base>
For example, with this:
[url "ssh://example.org/"]
pushInsteadOf = git://example.org/
a URL like "git://example.org/path/to/repo.git" will be rewritten to "ssh://example.org/path/to/repo.git" for pushes, but pulls will still use the original URL.
REMOTES
The name of one of the following can be used instead of a URL as <repository> argument:
- a remote in the Git configuration file: $GIT_DIR/config,
- a file in the $GIT_DIR/remotes directory, or
- a file in the $GIT_DIR/branches directory.
All of these also allow you to omit the refspec from the command line because they each contain a refspec which git will use by default.
Named remote in configuration file
You can choose to provide the name of a remote which you had previously configured using git-remote(1), git-config(1) or even by a manual edit to the
$GIT_DIR/config file. The URL of this remote will be used to access the repository. The refspec of this remote will be used by default when you do not
provide a refspec on the command line. The entry in the config file would appear like this:
[remote "<name>"]
url = <url>
pushurl = <pushurl>
push = <refspec>
fetch = <refspec>
The <pushurl> is used for pushes only. It is optional and defaults to <url>.
Named file in $GIT_DIR/remotes
You can choose to provide the name of a file in $GIT_DIR/remotes. The URL in this file will be used to access the repository. The refspec in this file will
be used as default when you do not provide a refspec on the command line. This file should have the following format:
URL: one of the above URL format
Push: <refspec>
Pull: <refspec>
Push: lines are used by git push and Pull: lines are used by git pull and git fetch. Multiple Push: and Pull: lines may be specified for additional branch
mappings.
Named file in $GIT_DIR/branches
You can choose to provide the name of a file in $GIT_DIR/branches. The URL in this file will be used to access the repository. This file should have the
following format:
<url>#<head>
<url> is required; #<head> is optional.
Depending on the operation, git will use one of the following refspecs, if you don’t provide one on the command line. <branch> is the name of this file in
$GIT_DIR/branches and <head> defaults to master.
git fetch uses:
refs/heads/<head>:refs/heads/<branch>
git push uses:
HEAD:refs/heads/<head>
https://git-scm.com/book/fr/v2/Utilitaires-Git-Sous-modules
Inspects, updates and manages submodules
git submodule
add [-b <branch>] [-f|--force] [--name <name>] [--reference <repository>] [--depth <depth>] [--] <repository> [<path>] # add the given repository as a submodule at the given path to the changeset to be committed next to the current project: the current project is termed the "superproject"
add [-b <branch>] [-f|--force] [--name <name>] [--reference <repository>] [--depth <depth>] [--] <repository> [<path>] # Add the given repository as a submodule at the given path to the changeset to be committed next to the current project: the current project is termed the "superproject".
status [--cached] [--recursive] [--] [<path>...] # Show the status of the submodules. This will print the SHA-1 of the currently checked out commit for each submodule, along with the submodule path and the output of git describe for the SHA-1.
init [--] [<path>...] # Initialize the submodules recorded in the index (which were added and committed elsewhere) by setting submodule.$name.url in .git/config.
deinit [-f|--force] (--all|[--] <path>...) # Unregister the given submodules, i.e. remove the whole submodule.$name section from .git/config together with their work tree.
update [--init] [--remote] [-N|--no-fetch] [--[no-]recommend-shallow] [-f|--force] [--checkout|--rebase|--merge] [--reference <repository>] [--depth <depth>] [--recursive] [--jobs <n>] # Update the registered submodules to match what the superproject expects by cloning missing submodules, fetching missing commits in submodules and updating the working tree of the submodules.
checkout # the commit recorded in the superproject will be checked out in the submodule on a detached HEAD.
rebase # the current branch of the submodule will be rebased onto the commit recorded in the superproject.
merge # the commit recorded in the superproject will be merged into the current branch in the submodule.
none # the submodule is not updated.
set-branch (-b|--branch) <branch> [--] <path>, set-branch (-d|--default) [--] <path> # Sets the default remote tracking branch for the submodule.
set-url [--] <path> <newurl> # Sets the URL of the specified submodule to <newurl>. Then, it will automatically synchronize the submodule’s new remote URL configuration.
summary [--cached|--files] [(-n|--summary-limit) <n>] [commit] [--] [<path>...] # Show commit summary between the given commit (defaults to HEAD) and working tree/index.
foreach [--recursive] <command> # Evaluates an arbitrary shell command in each checked out submodule.
sync [--recursive] [--] [<path>...] # Synchronizes submodules' remote URL configuration setting to the value specified in .gitmodules.
absorbgitdirs # If a git directory of a submodule is inside the submodule, move the git directory of the submodule into its superproject’s $GIT_DIR/modules path and then connect the git directory and its working directory by setting the core.worktree and adding a .git file pointing to the git directory embedded in the superprojects git directory.
Create, list, delete or verify a tag object signed with GPG
Add a tag reference in refs/tags/, unless -d/-l/-v is given to delete, list or verify tags
Unless -f is given, the named tag must not yet exist
If one of -a, -s, or -u <keyid> is passed, the command creates a tag object, and requires a tag message. Unless -m <msg> or -F <file> is given, an editor is started for the user to type in the tag message
If -m <msg> or -F <file> is given and -a, -s, and -u <keyid> are absent, -a is implied
Otherwise, a tag reference that points directly at the given object (i.e., a lightweight tag) is created
A GnuPG signed tag object will be created when -s or -u <keyid> is used. When -u <keyid> is not used, the committer identity for the current user is used to find the GnuPG key for signing. The configuration variable gpg.program is used to specify custom GnuPG binary
Tag objects (created with -a, -s, or -u) are called "annotated" tags; they contain a creation date, the tagger name and e-mail, a tagging message, and an optional GnuPG signature. Whereas a "lightweight" tag is simply a name for an object (usually a commit object)
Annotated tags are meant for release while lightweight tags are meant for private or temporary object labels. For this reason, some git commands for naming objects (like git describe) will ignore lightweight tags by default
git tag [-a | -s | -u <keyid>] [-f] [-m <msg> | -F <file>] [-e] <tagname> [<commit> | <object>]
git tag -d <tagname>...
git tag [-n[<num>]] -l [--contains <commit>] [--no-contains <commit>] [--points-at <object>] [--column[=<options>] | --no-column] [--create-reflog] [--sort=<key>] [--format=<format>] [--[no-]merged [<commit>]] [<pattern>...]
git tag -v [--format=<format>] <tagname>...
-a, --annotate # Make an unsigned, annotated tag object
-s, --sign # Make a GPG-signed tag, using the default e-mail address’s key
--no-sign # Override tag
-u <keyid>, --local-user=<keyid> # Make a GPG-signed tag, using the given key
-f, --force # Replace an existing tag with the given name (instead of failing)
-d, --delete # Delete existing tags with the given names
-v, --verify # Verify the GPG signature of the given tag names
-n<num> # <num> specifies how many lines from the annotation, if any, are printed when using -l
-l, --list # List tags
--sort=<key> # Sort based on the key given
--color[=<when>] # Respect any colors specified in the --format option
-i, --ignore-case # Sorting and filtering tags are case insensitive
--column[=<options>], --no-column # Display tag listing in columns
--contains [<commit>] # Only list tags which contain the specified commit (HEAD if not specified)
--no-contains [<commit>] # Only list tags which don’t contain the specified commit (HEAD if not specified)
--merged [<commit>] # Only list tags whose commits are reachable from the specified commit (HEAD if not specified), incompatible with --no-merged
--no-merged [<commit>] # Only list tags whose commits are not reachable from the specified commit (HEAD if not specified), incompatible with --merged
--points-at <object> # Only list tags of the given object (HEAD if not specified)
-m <msg>, --message=<msg> # Use the given tag message (instead of prompting)
-F <file>, --file=<file> # Take the tag message from the given file
-e, --edit # The message taken from file with -F and command line with -m are usually used as the tag message unmodified
--cleanup=<mode> # This option sets how the tag message is cleaned up
--create-reflog # Create a reflog for the tag
--format=<format> # A string that interpolates %(fieldname) from a tag ref being shown and the object it points at
<tagname> # The name of the tag to create, delete, or describe
<commit>, <object> # The object that the new tag will refer to, usually a commit
Fetch from and integrate with another repository or a local branch
Incorporates changes from a remote repository into the current branch. In its default mode, git pull is shorthand for git fetch followed by git merge FETCH_HEAD
More precisely, git pull runs git fetch with the given parameters and calls git merge to merge the retrieved branch heads into the current branch. With
--rebase, it runs git rebase instead of git merge
<repository> should be the name of a remote repository as passed to git-fetch(1). <refspec> can name an arbitrary remote ref (for example, the name of a tag) or even a collection of refs with corresponding remote-tracking branches (e.g., refs/heads/:refs/remotes/origin/), but usually it is the name of a branch in the remote repository
Default values for <repository> and <branch> are read from the "remote" and "merge" configuration for the current branch as set by git-branch(1) --track.
Assume the following history exists and the current branch is "master":
A---B---C master on origin
/
D---E---F---G master
^
origin/master in your repository
Then "git pull" will fetch and replay the changes from the remote master branch since it diverged from the local master (i.e., E) until its current commit (C) on top of master and record the result in a new commit along with the names of the two parent commits and a log message from the user describing the changes.
A---B---C origin/master
/ \
D---E---F---G---H master
See git-merge(1) for details, including how conflicts are presented and handled.
In Git 1.7.0 or later, to cancel a conflicting merge, use git reset --merge. Warning: In older versions of Git, running git pull with uncommitted changes is discouraged: while possible, it leaves you in a state that may be hard to back out of in the case of a conflict.
If any of the remote changes overlap with local uncommitted changes, the merge will be automatically canceled and the work tree untouched. It is generally best to get any local changes in working order before pulling or stash them away with git-stash(1).
git pull [<options>] [<repository> [<refspec>...]]
-q, --quiet # This is passed to both underlying git-fetch to squelch reporting of during transfer, and underlying git-merge to squelch output during merging
-v, --verbose # Pass --verbose to git-fetch and git-merge
--[no-]recurse-submodules[=yes|on-demand|no] # This option controls if new commits of all populated submodules should be fetched and updated, too
Options related to merging
--commit, --no-commit # Perform the merge and commit the result
--edit, -e, --no-edit # Invoke an editor before committing successful mechanical merge to further edit the auto-generated merge message, so that the user can explain and justify the merge
--cleanup=<mode> # This option determines how the merge message will be cleaned up before committing
--ff, --no-ff, --ff-only # Specifies how a merge is handled when the merged-in history is already a descendant of the current history
-S[<keyid>], --gpg-sign[=<keyid>] # GPG-sign the resulting merge commit
--log[=<n>], --no-log # In addition to branch names, populate the log message with one-line descriptions from at most <n> actual commits that are being merged
--signoff, --no-signoff # Add Signed-off-by line by the committer at the end of the commit log message
--stat, -n, --no-stat # Show a diffstat at the end of the merge
--squash, --no-squash # Produce the working tree and index state as if a real merge happened (except for the merge information), but do not actually make a commit, move the
--no-verify # This option bypasses the pre-merge and commit-msg hooks
-s <strategy>, --strategy=<strategy> # Use the given merge strategy; can be supplied more than once to specify them in the order they should be tried
-X <option>, --strategy-option=<option> # Pass merge strategy specific option through to the merge strategy
--verify-signatures, --no-verify-signatures # Verify that the tip commit of the side branch being merged is signed with a valid key, i
--summary, --no-summary # Synonyms to --stat and --no-stat; these are deprecated and will be removed in the future
--allow-unrelated-histories # By default, git merge command refuses to merge histories that do not share a common ancestor
-r, --rebase[=false|true|merges|preserve|interactive] # When true, rebase the current branch on top of the upstream branch after fetching
--no-rebase # Override earlier --rebase
--autostash, --no-autostash # Before starting rebase, stash local modifications away (see git-stash(1)) if needed, and apply the stash entry when done
Options related to fetching
--all # Fetch all remotes
-a, --append # Append ref names and object names of fetched refs to the existing contents of
--depth=<depth> # Limit fetching to the specified number of commits from the tip of each remote branch history
--deepen=<depth> # Similar to --depth, except it specifies the number of commits from the current shallow boundary instead of from the tip of each remote branch history
--shallow-since=<date> # Deepen or shorten the history of a shallow repository to include all reachable commits after <date>
--shallow-exclude=<revision> # Deepen or shorten the history of a shallow repository to exclude commits reachable from a specified remote branch or tag
--unshallow # If the source repository is complete, convert a shallow repository to a complete one, removing all the limitations imposed by shallow repositories
--update-shallow # By default when fetching from a shallow repository, git fetch refuses refs that require updating
--negotiation-tip=<commit|glob> # By default, Git will report, to the server, commits reachable from all local refs to find common commits in an attempt to reduce the size of the to-be-received packfile
-f, --force # When git fetch is used with <src>:<dst> refspec it may refuse to update the local branch as discussed in the <refspec> part of the git-fetch(1) documentation
-k, --keep # Keep downloaded pack
--no-tags # By default, tags that point at objects that are downloaded from the remote repository are fetched and stored locally
-u, --update-head-ok # By default git fetch refuses to update the head which corresponds to the current branch
--upload-pack <upload-pack> # When given, and the repository to fetch from is handled by git fetch-pack, --exec=<upload-pack> is passed to the command to specify non-default path for the command run on the other end
--progress # Progress status is reported on the standard error stream by default when it is attached to a terminal, unless -q is specified
-o <option>, --server-option=<option> # Transmit the given string to the server when communicating using protocol version 2
--show-forced-updates # By default, git checks if a branch is force-updated during fetch
--no-show-forced-updates # By default, git checks if a branch is force-updated during fetch
-4, --ipv4 # Use IPv4 addresses only, ignoring IPv6 addresses
-6, --ipv6 # Use IPv6 addresses only, ignoring IPv4 addresses
<repository> # The "remote" repository that is the source of a fetch or pull operation
<refspec> # Specifies which refs to fetch and which local refs to update
examples
Update the remote-tracking branches for the repository you cloned from, then merge one of them into your current branch:
git pull
git pull origin
Normally the branch merged in is the HEAD of the remote repository, but the choice is determined by the branch.<name>.remote and branch.<name>.merge
options; see git-config(1) for details.
Merge into the current branch the remote branch next:
git pull origin next
This leaves a copy of next temporarily in FETCH_HEAD, but does not update any remote-tracking branches. Using remote-tracking branches, the same can be
done by invoking fetch and merge:
git fetch origin
git merge origin/next
If you tried a pull which resulted in complex conflicts and would want to start over, you can recover with git reset
Download objects and refs from another repository
Fetch branches and/or tags (collectively, "refs") from one or more other repositories, along with the objects necessary to complete their histories. Remote-tracking branches are updated (see the description of <refspec> below for ways to control this behavior)
By default, any tag that points into the histories being fetched is also fetched; the effect is to fetch tags that point at branches that you are interested in. This default behavior can be changed by using the --tags or --no-tags options or by configuring remote.<name>.tagOpt. By using a refspec that fetches tags explicitly, you can fetch tags that do not point into branches you are interested in as well
git fetch can fetch from either a single named repository or URL, or from several repositories at once if <group> is given and there is a remotes.<group> entry in the configuration file
When no remote is specified, by default the origin remote will be used, unless there’s an upstream branch configured for the current branch
The names of refs that are fetched, together with the object names they point at, are written to .git/FETCH_HEAD. This information may be used by
scripts or other git commands, such as git-pull(1)
git fetch [<options>] [<repository> [<refspec>...]]
git fetch [<options>] <group>
git fetch --multiple [<options>] [(<repository> | <group>)...]
git fetch --all [<options>]
--all # Fetch all remotes
-a, --append # Append ref names and object names of fetched refs to the existing contents of .git/FETCH_HEAD. Without this option old data in .git/FETCH_HEAD will be overwritten
--depth=<depth> # Limit fetching to the specified number of commits from the tip of each remote branch history. If fetching to a shallow repository created by git clone with --depth=<depth> option, deepen or shorten the history to the specified number of commits. Tags for the deepened commits are not fetched
--deepen=<depth> # Similar to --depth, except it specifies the number of commits from the current shallow boundary instead of from the tip of each remote branch history
--shallow-since=<date> # Deepen or shorten the history of a shallow repository to include all reachable commits after <date>
--shallow-exclude=<revision> # Deepen or shorten the history of a shallow repository to exclude commits reachable from a specified remote branch or tag. This option can be specified multiple times
--unshallow # If the source repository is complete, convert a shallow repository to a complete one, removing all the limitations imposed by shallow repositories
--update-shallow # By default when fetching from a shallow repository, git fetch refuses refs that require updating .git/shallow. This option updates .git/shallow and accept such refs
--negotiation-tip=<commit|glob> # By default, Git will report, to the server, commits reachable from all local refs to find common commits in an attempt to reduce the size of the to-be-received packfile. If specified, Git will only report commits reachable from the given tips. This is useful to speed up fetches when the user knows which local ref is likely to have commits in common with the upstream ref being fetched
--dry-run # Show what would be done, without making any changes
-f, --force # When git fetch is used with <src>:<dst> refspec it may refuse to update the local branch as discussed in the <refspec> part below. This option overrides that check
-k, --keep # Keep downloaded pack
--multiple # Allow several <repository> and <group> arguments to be specified. No <refspec>s may be specified
--[no-]auto-gc # Run git gc --auto at the end to perform garbage collection if needed. This is enabled by default
--[no-]write-commit-graph # Write a commit-graph after fetching. This overrides the config setting fetch.writeCommitGraph
-p, --prune # Before fetching, remove any remote-tracking references that no longer exist on the remote. Tags are not subject to pruning if they are fetched only because of the default tag auto-following or due to a --tags option. However, if tags are fetched due to an explicit refspec (either on the command line or in the remote configuration, for example if the remote was cloned with the --mirror option), then they are also subject to pruning. Supplying --prune-tags is a shorthand for providing the tag refspec
-P, --prune-tags # Before fetching, remove any local tags that no longer exist on the remote if --prune is enabled. This option should be used more carefully, unlike --prune it will remove any local references (local tags) that have been created. This option is a shorthand for providing the explicit tag refspec along with --prune, see the discussion about that in its documentation
-n, --no-tags # By default, tags that point at objects that are downloaded from the remote repository are fetched and stored locally. This option disables this automatic tag following. The default behavior for a remote may be specified with the remote.<name>.tagOpt setting
--refmap=<refspec> # When fetching refs listed on the command line, use the specified refspec (can be given more than once) to map the refs to remote-tracking branches, instead of the values of remote.*.fetch configuration variables for the remote repository
-t, --tags # Fetch all tags from the remote (i.e., fetch remote tags refs/tags/* into local tags with the same name), in addition to whatever else would otherwise be fetched. Using this option alone does not subject tags to pruning, even if --prune is used (though tags may be pruned anyway if they are also the destination of an explicit refspec; see --prune)
--recurse-submodules[=yes|on-demand|no] # This option controls if and under what conditions new commits of populated submodules should be fetched too. It can be used as a boolean option to completely disable recursion when set to no or to unconditionally recurse into all populated submodules when set to yes, which is the default when this option is used without any value. Use on-demand to only recurse into a populated submodule when the superproject retrieves a commit that updates the submodule’s reference to a commit that isn’t already in the local submodule clone
-j, --jobs=<n> # Number of parallel children to be used for all forms of fetching
--no-recurse-submodules # Disable recursive fetching of submodules (this has the same effect as using the --recurse-submodules=no option)
--set-upstream # If the remote is fetched successfully, pull and add upstream (tracking) reference, used by argument-less git-pull(1) and other commands. For more information, see branch.<name>.merge and branch.<name>.remote in git-config(1)
--submodule-prefix=<path> # Prepend <path> to paths printed in informative messages such as "Fetching submodule foo". This option is used internally when recursing over submodules
--recurse-submodules-default=[yes|on-demand] # This option is used internally to temporarily provide a non-negative default value for the --recurse-submodules option. All other methods of configuring fetch’s submodule recursion (such as settings in gitmodules(5) and git-config(1)) override this option, as does specifying --[no-]recurse-submodules directly
-u, --update-head-ok # By default git fetch refuses to update the head which corresponds to the current branch. This flag disables the check. This is purely for the internal use for git pull to communicate with git fetch, and unless you are implementing your own Porcelain you are not supposed to use it
--upload-pack <upload-pack> # When given, and the repository to fetch from is handled by git fetch-pack, --exec=<upload-pack> is passed to the command to specify non-default path for the command run on the other end
-q, --quiet # Pass --quiet to git-fetch-pack and silence any other internally used git commands. Progress is not reported to the standard error stream
-v, --verbose # Be verbose
--progress # Progress status is reported on the standard error stream by default when it is attached to a terminal, unless -q is specified. This flag forces progress status even if the standard error stream is not directed to a terminal
-o <option>, --server-option=<option> # Transmit the given string to the server when communicating using protocol version 2. The given string must not contain a NUL or LF character. The server’s handling of server options, including unknown ones, is server-specific. When multiple --server-option=<option> are given, they are all sent to the other side in the order listed on the command line
--show-forced-updates # By default, git checks if a branch is force-updated during fetch. This can be disabled through fetch.showForcedUpdates, but the --show-forced-updates option guarantees this check occurs
--no-show-forced-updates # By default, git checks if a branch is force-updated during fetch. Pass --no-show-forced-updates or set fetch.showForcedUpdates to false to skip this check for performance reasons. If used during git-pull the --ff-only option will still check for forced updates before attempting a fast-forward update
-4, --ipv4 # Use IPv4 addresses only, ignoring IPv6 addresses
-6, --ipv6 # Use IPv6 addresses only, ignoring IPv4 addresses
<repository> # The "remote" repository that is the source of a fetch or pull operation. This parameter can be either a URL or the name of a remote
<group> # A name referring to a list of repositories as the value of remotes.<group> in the configuration file
<refspec> # Specifies which refs to fetch and which local refs to update. When no <refspec>s appear on the command line, the refs to fetch are read from remote.<repository>.fetch variables instead
examples
Update the remote-tracking branches
git fetch origin
The above command copies all branches from the remote refs/heads/ namespace and stores them to the local refs/remotes/origin/ namespace,
unless the branch.<name>.fetch option is used to specify a non-default refspec
Using refspecs explicitly:
git fetch origin +pu:pu maint:tmp
This updates (or creates, as necessary) branches pu and tmp in the local repository by fetching from the branches (respectively) pu and maint
from the remote repository
The pu branch will be updated even if it does not fast-forward, because it is prefixed with a plus sign; tmp will not be
Peek at a remote’s branch, without configuring the remote in your local repository
git fetch git://git.kernel.org/pub/scm/git/git.git maint
git log FETCH_HEAD
The first command fetches the maint branch from the repository at git://git.kernel.org/pub/scm/git/git.git and the second command uses
FETCH_HEAD to examine the branch with git-log(1). The fetched objects will eventually be removed by git’s built-in housekeeping
Update remote refs along with associated objects
Updates remote refs using local refs, while sending objects necessary to complete the given refs
You can make interesting things happen to a repository every time you push into it, by setting up hooks there. See documentation for git-receive-
pack(1)
When the command line does not specify where to push with the <repository> argument, branch.*.remote configuration for the current branch is
consulted to determine where to push. If the configuration is missing, it defaults to origin
When the command line does not specify what to push with <refspec>... arguments or --all, --mirror, --tags options, the command finds the default
<refspec> by consulting remote.*.push configuration, and if it is not found, honors push.default configuration to decide what to push (See git-
config(1) for the meaning of push.default)
When neither the command-line nor the configuration specify what to push, the default behavior is used, which corresponds to the simple value for
push.default: the current branch is pushed to the corresponding upstream branch, but as a safety measure, the push is aborted if the upstream
branch does not have the same name as the local one
git push [--all | --mirror | --tags] [--follow-tags] [--atomic] [-n | --dry-run] [--receive-pack=<git-receive-pack>] [--repo=<repository>] [-f | --force] [-d | --delete] [--prune] [-v | --verbose] [-u | --set-upstream] [-o <string> | --push-option=<string>] [--[no-]signed|--signed=(true|false|if-asked)] [--force-with-lease[=<refname>[:<expect>]]] [--no-verify] [<repository> [<refspec>...]]
<repository> # The "remote" repository that is destination of a push operation. This parameter can be either a URL (see the section GIT URLS below) or the name of a remote (see the section REMOTES below)
<refspec>... # Specify what destination ref to update with what source object. The format of a <refspec> parameter is an optional plus +, followed by the source object <src>, followed by a colon :, followed by the destination ref <dst>
--all # Push all branches (i.e. refs under refs/heads/); cannot be used with other <refspec>
--prune # Remove remote branches that don’t have a local counterpart. For example a remote branch tmp will be removed if a local branch with the same name doesn’t exist any more. This also respects refspecs, e.g. git push --prune remote refs/heads/*:refs/tmp/* would make sure that remote refs/tmp/foo will be removed if refs/heads/foo doesn’t exist
--mirror # Instead of naming each ref to push, specifies that all refs under refs/ (which includes but is not limited to refs/heads/, refs/remotes/, and refs/tags/) be mirrored to the remote repository. Newly created local refs will be pushed to the remote end, locally updated refs will be force updated on the remote end, and deleted refs will be removed from the remote end. This is the default if the configuration option remote.<remote>.mirror is set
-n, --dry-run # Do everything except actually send the updates
--porcelain # Produce machine-readable output. The output status line for each ref will be tab-separated and sent to stdout instead of stderr. The full symbolic names of the refs will be given
-d, --delete # All listed refs are deleted from the remote repository. This is the same as prefixing all refs with a colon
--tags # All refs under refs/tags are pushed, in addition to refspecs explicitly listed on the command line
--follow-tags # Push all the refs that would be pushed without this option, and also push annotated tags in refs/tags that are missing from the remote but are pointing at commit-ish that are reachable from the refs being pushed. This can also be specified with configuration variable push.followTags. For more information, see push.followTags in git-config(1)
--[no-]signed, --signed=(true|false|if-asked) # GPG-sign the push request to update refs on the receiving side, to allow it to be checked by the hooks and/or be logged. If false or --no-signed, no signing will be attempted. If true or --signed, the push will fail if the server does not support signed pushes. If set to if-asked, sign if and only if the server supports signed pushes. The push will also fail if the actual call to gpg --sign fails. See git-receive-pack(1) for the details on the receiving end
--[no-]atomic # Use an atomic transaction on the remote side if available. Either all refs are updated, or on error, no refs are updated. If the server does not support atomic pushes the push will fail
-o <option>, --push-option=<option> # Transmit the given string to the server, which passes them to the pre-receive as well as the post-receive hook. The given string must not contain a NUL or LF character. When multiple --push-option=<option> are given, they are all sent to the other side in the order listed on the command line. When no --push-option=<option> is given from the command line, the values of configuration variable push.pushOption are used instead
--receive-pack=<git-receive-pack>, --exec=<git-receive-pack> # Path to the git-receive-pack program on the remote end. Sometimes useful when pushing to a remote repository over ssh, and you do not have the program in a directory on the default $PATH
--[no-]force-with-lease, --force-with-lease=<refname>, --force-with-lease=<refname>:<expect> # Usually, "git push" refuses to update a remote ref that is not an ancestor of the local ref used to overwrite it. This option overrides this restriction if the current value of the remote ref is the expected value. "git push" fails otherwise
-f, --force # Usually, the command refuses to update a remote ref that is not an ancestor of the local ref used to overwrite it. Also, when --force-with-lease option is used, the command refuses to update a remote ref whose current value does not match what is expected
--repo=<repository> # This option is equivalent to the <repository> argument. If both are specified, the command-line argument takes precedence
-u, --set-upstream # For every branch that is up to date or successfully pushed, add upstream (tracking) reference, used by argument-less git-pull(1) and other commands. For more information, see branch.<name>.merge in git-config(1)
--[no-]thin # These options are passed to git-send-pack(1). A thin transfer significantly reduces the amount of sent data when the sender and receiver share many of the same objects in common. The default is --thin
-q, --quiet # Suppress all output, including the listing of updated refs, unless an error occurs. Progress is not reported to the standard error stream
-v, --verbose # Run verbosely
--progress # Progress status is reported on the standard error stream by default when it is attached to a terminal, unless -q is specified. This flag forces progress status even if the standard error stream is not directed to a terminal
--no-recurse-submodules, --recurse-submodules=check|on-demand|only|no # May be used to make sure all submodule commits used by the revisions to be pushed are available on a remote-tracking branch. If check is used Git will verify that all submodule commits that changed in the revisions to be pushed are available on at least one remote of the submodule. If any commits are missing the push will be aborted and exit with non-zero status. If on-demand is used all submodules that changed in the revisions to be pushed will be pushed. If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status. If only is used all submodules will be recursively pushed while the superproject is left unpushed. A value of no or using --no-recurse-submodules can be used to override the push.recurseSubmodules configuration variable when no submodule recursion is required
--[no-]verify # Toggle the pre-push hook (see githooks(5)). The default is --verify, giving the hook a chance to prevent the push. With --no-verify, the hook is bypassed completely
-4, --ipv4 # Use IPv4 addresses only, ignoring IPv6 addresses
-6, --ipv6 # Use IPv6 addresses only, ignoring IPv4 addresses
OUTPUT
The output of "git push" depends on the transport method used; this section describes the output when pushing over the Git protocol (either
locally or via ssh)
The status of the push is output in tabular form, with each line representing the status of a single ref. Each line is of the form:
- <flag> <summary> <from> -> <to> (<reason>)
If --porcelain is used, then each line of the output is of the form:
- <flag> \t <from>:<to> \t <summary> (<reason>)
The status of up-to-date refs is shown only if --porcelain or --verbose option is used
flag
(space) # for a successfully pushed fast-forward;
+ # for a successful forced update;
- # for a successfully deleted ref;
* # for a successfully pushed new ref;
! # for a ref that was rejected or failed to push; and
= # for a ref that was up to date and did not need pushing
summary
For a successfully pushed ref
the summary shows the old and new values of the ref in a form suitable for using as an argument to git log (this is <old>..<new> in most cases, and <old>...<new> for forced non-fast-forward updates)
For a failed update, more details are given:
rejected # Git did not try to send the ref at all, typically because it is not a fast-forward and you did not force the update
remote rejected # The remote end refused the update. Usually caused by a hook on the remote side, or because the remote repository has one of the following safety options in effect: receive.denyCurrentBranch (for pushes to the checked out branch), receive.denyNonFastForwards (for forced non-fast-forward updates), receive.denyDeletes or receive.denyDeleteCurrent
remote failure # The remote end did not report the successful update of the ref, perhaps because of a temporary error on the remote side, a break in the network connection, or other transient error
from # The name of the local ref being pushed, minus its refs/<type>/ prefix. In the case of deletion, the name of the local ref is omitted
to # The name of the remote ref being updated, minus its refs/<type>/ prefix
reason # A human-readable explanation. In the case of successfully pushed refs, no explanation is needed. For a failed ref, the reason for failure is
described
examples
git push
# Works like git push <remote>, where <remote> is the current branch’s remote (or origin, if no remote is configured for the current branch)
git push origin
# Without additional configuration, pushes the current branch to the configured upstream (remote.origin.merge configuration variable) if it has the same name as the current branch, and errors out without pushing otherwise
#The default behavior of this command when no <refspec> is given can be configured by setting the push option of the remote, or the push.default configuration variable
# For example, to default to pushing only the current branch to origin use git config remote.origin.push HEAD. Any valid <refspec> (like the ones in the examples below) can be configured as the default for git push origin
git push origin:
# Push "matching" branches to origin. See <refspec> in the OPTIONS section above for a description of "matching" branches
git push origin master
# Find a ref that matches master in the source repository (most likely, it would find refs/heads/master), and update the same ref (e.g. refs/heads/master) in origin repository with it. If master did not exist remotely, it would be created
git push origin HEAD
# A handy way to push the current branch to the same name on the remote
git push mothership master:satellite/master dev:satellite/dev
# Use the source ref that matches master (e.g. refs/heads/master) to update the ref that matches satellite/master (most probably refs/remotes/satellite/master) in the mothership repository; do the same for dev and satellite/dev
# See the section describing <refspec>... above for a discussion of the matching semantics
# This is to emulate git fetch run on the mothership using git push that is run in the opposite direction in order to integrate the work done on satellite, and is often necessary when you can only make connection in one way (i.e. satellite can ssh into mothership but mothership cannot initiate connection to satellite because the latter is behind a firewall or does not run sshd)
# After running this git push on the satellite machine, you would ssh into the mothership and run git merge there to complete the emulation of git pull that were run on mothership to pull changes made on satellite
git push origin HEAD:master
# Push the current branch to the remote ref matching master in the origin repository. This form is convenient to push the current branch without thinking about its local name
git push origin master:refs/heads/experimental
# Create the branch experimental in the origin repository by copying the current master branch. This form is only needed to create a new branch or tag in the remote repository when the local name and the remote name are different; otherwise, the ref name on its own will work
git push origin :experimental
# Find a ref that matches experimental in the origin repository (e.g. refs/heads/experimental), and delete it
git push origin +dev:master
# Update the origin repository’s master branch with the dev branch, allowing non-fast-forward updates. This can leave unreferenced commits dangling in the origin repository. Consider the following situation, where a fast-forward is not possible:
o---o---o---A---B origin/master
\
X---Y---Z dev
The above command would change the origin repository to
A---B (unnamed branch)
/
o---o---o---X---Y---Z master
# Commits A and B would no longer belong to a branch with a symbolic name, and so would be unreachable. As such, these commits would be removed by a git gc command on the origin repository
List references in a remote repository
Displays references available in a remote repository along with the associated commit IDs
git ls-remote [--heads] [--tags] [--refs] [--upload-pack=<exec>] [-q | --quiet] [--exit-code] [--get-url] [--sort=<key>] [--symref] [<repository> [<refs>...]]
-h, --heads, -t, --tags # Limit to only refs/heads and refs/tags, respectively. These options are not mutually exclusive; when given both, references stored in refs/heads and refs/tags are displayed
--refs # Do not show peeled tags or pseudorefs like HEAD in the output
-q, --quiet # Do not print remote URL to stderr
--upload-pack=<exec> # Specify the full path of git-upload-pack on the remote host. This allows listing references from repositories accessed via SSH and where the SSH daemon does not use the PATH configured by the user
--exit-code # Exit with status "2" when no matching refs are found in the remote repository. Usually the command exits with status "0" to indicate it successfully talked with the remote repository, whether it found any matching refs
--get-url # Expand the URL of the given remote repository taking into account any "url.<base>.insteadOf" config setting (See git-config(1)) and exit without talking to the remote
--symref # In addition to the object pointed by it, show the underlying ref pointed by it when showing a symbolic ref. Currently, upload-pack only shows the symref HEAD, so it will be the only one shown by ls-remote
--sort=<key> # Sort based on the key given. Prefix - to sort in descending order of the value. Supports "version:refname" or "v:refname" (tag names are treated as versions). The "version:refname" sort order can also be affected by the "versionsort.suffix" configuration variable. See git-for- each-ref(1) for more sort options, but be aware keys like committerdate that require access to the objects themselves will not work for refs whose objects have not yet been fetched from the remote, and will give a missing object error
-o <option>, --server-option=<option> # Transmit the given string to the server when communicating using protocol version 2. The given string must not contain a NUL or LF character. When multiple --server-option=<option> are given, they are all sent to the other side in the order listed on the command line
<repository> # The "remote" repository to query. This parameter can be either a URL or the name of a remote (see the GIT URLS and REMOTES sections of git- fetch(1))
<refs>... # When unspecified, all references, after filtering done with --heads and --tags, are shown. When <refs>... are specified, only references matching the given patterns are displayed
examples
git ls-remote --tags ./
git ls-remote http://www.kernel.org/pub/scm/git/git.git master pu rc
git remote add korg http://www.kernel.org/pub/scm/git/git.git
git ls-remote --tags korg v\*
Manage set of tracked repositories
Manage the set of repositories ("remotes") whose branches you track
SUBCOMMANDS
subcommand | Designation |
---|---|
ADD | Adds a remote named <name> for the repository at <url> |
RENAME | REMOVE THE REMOTE NAMED <NAME> |
RM | Remove the remote named <name> |
SET-HEAD | Sets or deletes the default branch for the named remote |
SET-BRANCHES | Changes the list of branches tracked by the named remote |
GET-URL | Retrieves the URLs for a remote. Configurations for insteadOf and pushInsteadOf are expanded here |
SET-URL | Changes URLs for the remote. Sets first URL for remote <name> to <newurl> |
SHOW | Gives some information about the remote <name> |
PRUNE | Deletes stale references associated with <name> |
UPDATE | Fetch updates for remotes or remote groups in the repository as defined by remotes.<group> |
EXAMPLES | Fetch updates for remotes or remote groups in the repository as defined by remotes.<group> |
ADD
Adds a remote named <name> for the repository at <url>. The command git fetch <name> can then be used to create and update remote-tracking branches <name>/<branch>
git remote add [-t <branch>] [-m <master>] [-f] [--[no-]tags] [--mirror=<fetch|push>] <name> <url>
-f # git fetch <name> is run immediately after the remote information is set up
--tags # git fetch <name> imports every tag from the remote repository
--no-tags # git fetch <name> does not import tags from the remote repository. By default, only tags on fetched branches are imported
-t <branch> # instead of the default glob refspec for the remote to track all branches under the refs/remotes/<name>/ namespace, a refspec to track only <branch> is created. You can give more than one -t <branch> to track
-m <master> # a symbolic-ref refs/remotes/<name>/HEAD is set up to point at remote’s <master> branch
RENAME
Rename the remote named <old> to <new>. All remote-tracking branches and configuration settings for the remote are updated
In case <old> and <new> are the same, and <old> is a file under $GIT_DIR/remotes or $GIT_DIR/branches, the remote is converted to the configuration file format
git remote rename <old> <new>
RM
Remove the remote named <name>. All remote-tracking branches and configuration settings for the remote are removed
git remote remove <name>
SET-HEAD
Sets or deletes the default branch (i.e. the target of the symbolic-ref refs/remotes/<name>/HEAD) for the named remote. Having a default branch for a remote is not required, but allows the name of the remote to be specified in lieu of a specific branch. For example, if the default branch for origin is set to master, then origin may be specified wherever you would normally specify origin/master
git remote set-head <name> (-a | --auto | -d | --delete | <branch>)
-d, --delete # the symbolic ref refs/remotes/<name>/HEAD is deleted
-a, --auto # the remote is queried to determine its HEAD, then the symbolic-ref refs/remotes/<name>/HEAD is set to the same branch. e.g., if the remote HEAD is pointed at next, "git remote set-head origin -a" will set the
symbolic-ref refs/remotes/origin/HEAD to refs/remotes/origin/next. This will only work if refs/remotes/origin/next already exists; if not it must be fetched first
Use <branch> to set the symbolic-ref refs/remotes/<name>/HEAD explicitly. e.g., "git remote set-head origin master" will set the symbolic-ref refs/remotes/origin/HEAD to refs/remotes/origin/master. This will only work if
refs/remotes/origin/master already exists; if not it must be fetched first
SET-BRANCHES
Changes the list of branches tracked by the named remote. This can be used to track a subset of the available remote branches after the initial setup for a remote
The named branches will be interpreted as if specified with the -t option on the git remote add command line
git remote set-branches [--add] <name> <branch>...
--add # instead of replacing the list of currently tracked branches, adds to that list
GET-URL
Retrieves the URLs for a remote. Configurations for insteadOf and pushInsteadOf are expanded here. By default, only the first URL is listed
git remote get-url [--push] [--all] <name>
--push # push URLs are queried rather than fetch URLs
--all # all URLs for the remote will be listed
SET-URL
Changes URLs for the remote. Sets first URL for remote <name> that matches regex <oldurl> (first URL if no <oldurl> is given) to <newurl>. If <oldurl> doesn’t match any URL, an error occurs and nothing is changed
Note that the push URL and the fetch URL, even though they can be set differently, must still refer to the same place. What you pushed to the push URL should be what you would see if you immediately fetched from the fetch URL. If
you are trying to fetch from one place (e.g. your upstream) and push to another (e.g. your publishing repository), use two separate remotes
git remote set-url [--push] <name> <newurl> [<oldurl>]
git remote set-url --add [--push] <name> <newurl>
git remote set-url --delete [--push] <name> <url>
--push # push URLs are manipulated instead of fetch URLs
--add # instead of changing existing URLs, new URL is added
--delete # instead of changing existing URLs, all URLs matching regex <url> are deleted for remote <name>. Trying to delete all non-push URLs is an error
SHOW
Gives some information about the remote <name>
git remote [-v | --verbose] show [-n] <name>...
-n # the remote heads are not queried first with git ls-remote <name>; cached information is used instead
PRUNE
Deletes stale references associated with <name>. By default, stale remote-tracking branches under <name> are deleted, but depending on global configuration and the configuration of the remote we might even prune local tags that
haven’t been pushed there. Equivalent to git fetch --prune <name>, except that no new references will be fetched
git remote prune [-n | --dry-run] <name>...
--dry-run # report what branches will be pruned, but do not actually prune them
UPDATE
Fetch updates for remotes or remote groups in the repository as defined by remotes.<group>. If neither group nor remote is specified on the command line, the configuration parameter remotes.default will be used; if remotes.default is not defined, all remotes which do not have the configuration parameter remote.<name>.skipDefaultUpdate set to true will be updated
git remote [-v | --verbose] update [-p | --prune] [(<group> | <remote>)...]
--prune # run pruning against all the remotes that are updated
EXAMPLES
Add a new remote, fetch, and check out a branch from it
$ git remote
origin
$ git branch -r
origin/HEAD -> origin/master
origin/master
$ git remote add staging git://git.kernel.org/.../gregkh/staging.git
$ git remote
origin
staging
$ git fetch staging
...
From git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/staging
* [new branch] master -> staging/master
* [new branch] staging-linus -> staging/staging-linus
* [new branch] staging-next -> staging/staging-next
$ git branch -r
origin/HEAD -> origin/master
origin/master
staging/master
staging/staging-linus
staging/staging-next
$ git switch -c staging staging/master
...
Imitate git clone but track only selected branches
$ mkdir project.git
$ cd project.git
$ git init
$ git remote add -f -t master -m master origin git://example.com/git.git/
$ git merge origin
Shows the commit logs
The command takes options applicable to the git rev-list command to control what is shown and how, and options applicable to the git diff-* commands to control how the changes each commit introduces are shown
OPTIONS
git log [<options>] [<revision range>] [[--] <path>...]
--follow # Continue listing the history of a file beyond renames (works only for a single file)
--no-decorate, --decorate[=short|full|auto|no] # Print out the ref names of any commits that are shown
--decorate-refs=<pattern>, --decorate-refs-exclude=<pattern> # If no --decorate-refs is given, pretend as if all refs were included
--source # Print out the ref name given on the command line by which each commit was reached
--[no-]use-mailmap # Use mailmap file to map author and committer names and email addresses to canonical real names and email addresses
--full-diff # Without this flag, git log -p <path>
Note that this affects all diff-based output types, e
--log-size # Include a line “log size <number>” in the output for each commit, where <number> is the length of that commit’s message in bytes
-L <start>,<end>:<file>, -L :<funcname>:<file> # Trace the evolution of the line range given by "<start>,<end>" (or the function name regex <funcname>) within the <file>
<start> and <end> can take one of these forms:
- number # If <start> or <end> is a number, it specifies an absolute line number (lines count from 1)
- /regex/ # This form will use the first line matching the given POSIX regex
- +offset or -offset # This is only valid for <end> and will specify a number of lines before or after the line given by <start>
<revision range> # Show only commits in the specified revision range
[--] <path>... # Show only commits that are enough to explain how the files that match the specified paths came to be. See History Simplification below for details and other simplification modes
-<number>, -n <number>, --max-count=<number> # Limit the number of commits to output
--skip=<number> # Skip number commits before starting to show the commit output
--since=<date>, --after=<date> # Show commits more recent than a specific date
--until=<date>, --before=<date> # Show commits older than a specific date
--author=<pattern>, --committer=<pattern> # Limit the commits output to ones with author/committer header lines that match the specified pattern (regular expression)
--grep-reflog=<pattern> # Limit the commits output to ones with reflog entries that match the specified pattern (regular expression)
--grep=<pattern> # Limit the commits output to ones with log message that matches the specified pattern (regular expression)
--all-match # Limit the commits output to ones that match all given --grep, instead of ones that match at least one
--invert-grep # Limit the commits output to ones with log message that do not match the pattern specified with --grep=<pattern>
-i, --regexp-ignore-case # Match the regular expression limiting patterns without regard to letter case
--basic-regexp # Consider the limiting patterns to be basic regular expressions; this is the default
-E, --extended-regexp # Consider the limiting patterns to be extended regular expressions instead of the default basic regular expressions
-F, --fixed-strings # Consider the limiting patterns to be fixed strings (don’t interpret pattern as a regular expression)
-P, --perl-regexp # Consider the limiting patterns to be Perl-compatible regular expressions
--remove-empty # Stop when a given path disappears from the tree
--merges # Print only merge commits
--no-merges # Do not print commits with more than one parent
--min-parents=<number>, --max-parents=<number>, --no-min-parents, --no-max-parents # Show only commits which have at least (or at most) that many parent commits
--first-parent # Follow only the first parent commit upon seeing a merge commit
--not # Reverses the meaning of the ^ prefix (or lack thereof) for all following revision specifiers, up to the next --not
--all # Pretend as if all the refs in refs/, along with HEAD, are listed on the command line as <commit>
--branches[=<pattern>] # Pretend as if all the refs in refs/heads are listed on the command line as <commit>
--tags[=<pattern>] # Pretend as if all the refs in refs/tags are listed on the command line as <commit>
--remotes[=<pattern>] # Pretend as if all the refs in refs/remotes are listed on the command line as <commit>
--glob=<glob-pattern> # Pretend as if all the refs matching shell glob <glob-pattern> are listed on the command line as <commit>
--exclude=<glob-pattern> # Do not include refs matching <glob-pattern> that the next --all, --branches, --tags, --remotes, or --glob would otherwise consider
--reflog # Pretend as if all objects mentioned by reflogs are listed on the command line as <commit>
--alternate-refs # Pretend as if all objects mentioned as ref tips of alternate repositories were listed on the command line
--single-worktree # By default, all working trees will be examined by the following options when there are more than one (see git-worktree(1)): --all, --reflog and --indexed-objects
--ignore-missing # Upon seeing an invalid object name in the input, pretend as if the bad input was not given
--bisect # Pretend as if the bad bisection ref refs/bisect/bad was listed and as if it was followed by --not and the good bisection refs refs/bisect/good-* on the command line
--stdin # In addition to the <commit> listed on the command line, read them from the standard input
--cherry-mark # Like --cherry-pick (see below) but mark equivalent commits with = rather than omitting them, and inequivalent ones with +
--cherry-pick # Omit any commit that introduces the same change as another commit on the “other side” when the set of commits are limited with symmetric difference
--left-only, --right-only # List only commits on the respective side of a symmetric difference, i
--cherry # A synonym for --right-only --cherry-mark --no-merges; useful to limit the output to the commits on our side and mark those that have been applied to the other side of a forked history with git log --cherry upstream
-g, --walk-reflogs # Instead of walking the commit ancestry chain, walk reflog entries from the most recent one to older ones
--merge # After a failed merge, show refs that touch files having a conflict and don’t exist on all heads to merge
--boundary # Output excluded boundary commits
<paths> # Commits modifying the given <paths> are selected
--simplify-by-decoration # Commits that are referred by some branch or tag are selected
--full-history # Same as the default mode, but does not prune some history
--dense # Only the selected commits are shown, plus some to have a meaningful history
--sparse # All commits in the simplified history are shown
--simplify-merges # Additional option to --full-history to remove some needless merges from the resulting history, as there are no selected commits contributing to this merge
--ancestry-path # When given a range of commits to display (e
--full-history without parent rewriting # This mode differs from the default in one point: always follow all parents of a merge, even if it is TREESAME to one of them
--full-history with parent rewriting # Ordinary commits are only included if they are !TREESAME (though this can be changed, see --sparse below)
--dense # Commits that are walked are included if they are not TREESAME to any parent
--sparse # All commits that are walked are included
--simplify-merges # First, build a history graph in the same way that --full-history with parent rewriting does (see above)
--ancestry-path # Limit the displayed commits to those directly on the ancestry chain between the “from” and “to” commits in the given commit range
--date-order # Show no parents before all of its children are shown, but otherwise show commits in the commit timestamp order
--author-date-order # Show no parents before all of its children are shown, but otherwise show commits in the author timestamp order
--topo-order # Show no parents before all of its children are shown, and avoid showing commits on multiple lines of history intermixed
--reverse # Output the commits chosen to be shown (see Commit Limiting section above) in reverse order
--no-walk[=(sorted|unsorted)] # Only show the given commits, but do not traverse their ancestors
--do-walk # Overrides a previous --no-walk
Commit Formatting
--pretty[=<format>], --format=<format> # Pretty-print the contents of the commit logs in a given format, where <format> can be one of oneline, short, medium, full, fuller, reference, email, raw, format:<string> and tformat:<string>
--abbrev-commit # Instead of showing the full 40-byte hexadecimal commit object name, show only a partial prefix
--no-abbrev-commit # Show the full 40-byte hexadecimal commit object name
--oneline # This is a shorthand for "--pretty=oneline --abbrev-commit" used together
--encoding=<encoding> # The commit objects record the encoding used for the log message in their encoding header; this option can be used to tell the command to re-code the commit log message in the encoding preferred by the user
--expand-tabs=<n>, --expand-tabs, --no-expand-tabs # Perform a tab expansion (replace each tab with enough spaces to fill to the next display column that is multiple of <n>) in the log message before showing it in the output
--notes[=<ref>] # Show the notes (see git-notes(1)) that annotate the commit, when showing the commit log message
--no-notes # Do not show notes
--show-notes[=<ref>], --[no-]standard-notes # These options are deprecated
--show-signature # Check the validity of a signed commit object by passing the signature to gpg --verify and show the output
--relative-date # Synonym for --date=relative
--date=<format> # Only takes effect for dates shown in human-readable format, such as when using --pretty
--parents # Print also the parents of the commit (in the form "commit parent
--children # Print also the children of the commit (in the form "commit child
--left-right # Mark which side of a symmetric difference a commit is reachable from
--graph # Draw a text-based graphical representation of the commit history on the left hand side of the output
--show-linear-break[=<barrier>] # When --graph is not used, all history branches are flattened which can make it hard to see that the two consecutive commits do not belong to a linear branch
Diff Formatting
Listed below are options that control the formatting of diff output
-c # With this option, diff output for a merge commit shows the differences from each of the parents to the merge result simultaneously instead of showing pairwise diff between a parent and the result one at a time
--cc # This flag implies the -c option and further compresses the patch output by omitting uninteresting hunks whose contents in the parents have only two variants and the merge result picks one of them without modification
--combined-all-paths # This flag causes combined diffs (used for merge commits) to list the name of the file from all parents
-m # This flag makes the merge commits show the full diff like regular commits; for each merge parent, a separate log entry and diff is generated
-r # Show recursive diffs
-t # Show the tree objects in the diff output
PRETTY FORMATS
If the commit is a merge, and if the pretty-format is not oneline, email or raw, an additional line is inserted before the Author: line. This line begins with "Merge: " and the hashes of ancestral commits are printed, separated by spaces. Note that the listed commits may not necessarily be the list of the direct parent commits if you have limited your view of history: for example, if you are only interested in changes related to a certain directory or file
There are several built-in formats, and you can define additional formats by setting a pretty.<name> config option to either another format name, or a format: string, as described below (see git-config(1))
Here are the details of the built-in formats:
- oneline
- short
- medium
- full
- fuller
- reference
- raw
- format:<string> # see man for details
- tformat:<string> # see man for details
COMMON DIFF OPTIONS
-p, -u, --patch # Generate patch (see section on generating patches)
-s, --no-patch # Suppress diff output
-U<n>, --unified=<n> # Generate diffs with <n> lines of context instead of the usual three
--output=<file> # Output to a specific file instead of stdout
--output-indicator-new=<char>, --output-indicator-old=<char>, --output-indicator-context=<char> # Specify the character used to indicate new, old or context lines in the generated patch
--raw # For each commit, show a summary of changes using the raw diff format
--patch-with-raw # Synonym for -p --raw
--indent-heuristic # Enable the heuristic that shifts diff hunk boundaries to make patches easier to read
--no-indent-heuristic # Disable the indent heuristic
--minimal # Spend extra time to make sure the smallest possible diff is produced
--patience # Generate a diff using the "patience diff" algorithm
--histogram # Generate a diff using the "histogram diff" algorithm
--anchored=<text> # Generate a diff using the "anchored diff" algorithm
--diff-algorithm={patience|minimal|histogram|myers} # Choose a diff algorithm
The variants are as follows:
default, myers # The basic greedy diff algorithm
minimal # Spend extra time to make sure the smallest possible diff is produced
patience # Use "patience diff" algorithm when generating patches
histogram # This algorithm extends the patience algorithm to "support low-occurrence common elements"
--stat[=<width>[,<name-width>[,<count>]]] # Generate a diffstat
--compact-summary # Output a condensed summary of extended header information such as file creations or deletions ("new" or "gone", optionally "+l" if it’s a symlink) and mode changes ("+x" or "-x" for adding or removing executable bit respectively) in diffstat
--numstat # Similar to --stat, but shows number of added and deleted lines in decimal notation and pathname without abbreviation, to make it more machine friendly
--shortstat # Output only the last line of the --stat format containing total number of modified files, as well as number of added and deleted lines
-X[<param1,param2,
The following parameters are available:
changes # Compute the dirstat numbers by counting the lines that have been removed from the source, or added to the destination
lines # Compute the dirstat numbers by doing the regular line-based diff analysis, and summing the removed/added line counts
files # Compute the dirstat numbers by counting the number of files changed
cumulative # Count changes in a child directory for the parent directory as well
<limit> # An integer parameter specifies a cut-off percent (3% bygit log [<options>] [<revision range>] [[--] <path>...] default)
Example: The following will count changed files, while ignoring directories with less than 10% of the total amount of changed files, and accumulating child directory counts in the parent directories: --dirstat=files,10,cumulative
--cumulative # Synonym for --dirstat=cumulative
--summary # Output a condensed summary of extended header information such as creations, renames and mode changes
--patch-with-stat # Synonym for -p --stat
-z # Separate the commits with NULs instead of with new newlines
--name-only # Show only names of changed files
--name-status # Show only names and status of changed files
--submodule[=<format>] # Specify how differences in submodules are shown
--color[=<when>] # Show colored diff
--no-color # Turn off colored diff
--color-moved[=<mode>] # Moved lines of code are colored differently
The mode must be one of:
no # Moved lines are not highlighted
default # Is a synonym for zebra
plain # Any line that is added in one location and was removed in another location will be colored with color
blocks # Blocks of moved text of at least 20 alphanumeric characters are detected greedily
zebra # Blocks of moved text are detected as in blocks mode
dimmed-zebra # Similar to zebra, but additional dimming of uninteresting parts of moved code is performed
--no-color-moved # Turn off move detection
--color-moved-ws=<modes> # This configures how whitespace is ignored when performing the move detection for --color-moved
These modes can be given as a comma separated list:
no # Do not ignore whitespace when performing move detection
ignore-space-at-eol # Ignore changes in whitespace at EOL
ignore-space-change # Ignore changes in amount of whitespace
ignore-all-space # Ignore whitespace when comparing lines
allow-indentation-change # Initially ignore any whitespace in the move detection, then group the moved code blocks only into a block if the change in whitespace is the same per line
--no-color-moved-ws # Do not ignore whitespace when performing move detection
--word-diff[=<mode>] # Show a word diff, using the <mode> to delimit changed words
The <mode> defaults to plain, and must be one of:
color # Highlight changed words using only colors
plain # Show words as [-removed-] and {+added+}
porcelain # Use a special line-based format intended for script consumption
none # Disable word diff again
--word-diff-regex=<regex> # Use <regex> to decide what a word is, instead of considering runs of non-whitespace to be a word
--color-words[=<regex>] # Equivalent to --word-diff=color plus (if a regex was specified) --word-diff-regex=<regex>
--no-renames # Turn off rename detection, even when the configuration file gives the default to do so
--[no-]rename-empty # Whether to use empty blobs as rename source
--check # Warn if changes introduce conflict markers or whitespace errors
--ws-error-highlight=<kind> # Highlight whitespace errors in the context, old or new lines of the diff
--full-index # Instead of the first handful of characters, show the full pre- and post-image blob object names on the "index" line when generating patch format output
--binary # In addition to --full-index, output a binary diff that can be applied with git-apply
--abbrev[=<n>] # Instead of showing the full 40-byte hexadecimal object name in diff-raw format output and diff-tree header lines, show only a partial prefix
-B[<n>][/<m>], --break-rewrites[=[<n>][/<m>]] # Break complete rewrite changes into pairs of delete and create
-M[<n>], --find-renames[=<n>] # If generating diffs, detect and report renames for each commit
-C[<n>], --find-copies[=<n>] # Detect copies as well as renames
--find-copies-harder # For performance reasons, by default, -C option finds copies only if the original file of the copy was modified in the same changeset
-D, --irreversible-delete # Omit the preimage for deletes, i.e. print only the header but not the diff between the preimage and /dev/null
-l<num> # The -M and -C options require O(n^2) processing time where n is the number of potential rename/copy targets
--diff-filter=[(A|C|D|M|R|T|U|X|B)...[*]] # Select only files that are Added (A), Copied (C), Deleted (D), Modified (M), Renamed (R), have their type (i.e. regular file, symlink, submodule, ...) changed (T), are Unmerged (U), are Unknown (X), or have had their pairing Broken (B)
-S<string> # Look for differences that change the number of occurrences of the specified string (i.e. addition/deletion) in a file. Intended for the scripter’s use
-G<regex> # Look for differences whose patch text contains added/removed lines that match <regex>
--find-object=<object-id> # Look for differences that change the number of occurrences of the specified object
--pickaxe-all # When -S or -G finds a change, show all the changes in that changeset, not just the files that contain the change in <string>
--pickaxe-regex # Treat the <string> given to -S as an extended POSIX regular expression to match
-O<orderfile> # Control the order in which files appear in the output
<orderfile> is parsed as follows:
- Blank lines are ignored, so they can be used as separators for readability
- Lines starting with a hash ("#") are ignored, so they can be used for comments. Add a backslash ("\\") to the beginning of the pattern if it starts with a hash
- Each other line contains a single pattern
-R # Swap two inputs; that is, show differences from index or on-disk file to tree contents
--relative[=<path>] # When run from a subdirectory of the project, it can be told to exclude changes outside the directory and show pathnames relative to it with this option
-a, --text # Treat all files as text
--ignore-cr-at-eol # Ignore carriage-return at the end of line when doing a comparison
--ignore-space-at-eol # Ignore changes in whitespace at EOL
-b, --ignore-space-change # Ignore changes in amount of whitespace
-w, --ignore-all-space # Ignore whitespace when comparing lines
--ignore-blank-lines # Ignore changes whose lines are all blank
--inter-hunk-context=<lines> # Show the context between diff hunks, up to the specified number of lines, thereby fusing hunks that are close to each other
-W, --function-context # Show whole surrounding functions of changes
--ext-diff # Allow an external diff helper to be executed
--no-ext-diff # Disallow external diff drivers
--textconv, --no-textconv # Allow (or disallow) external text conversion filters to be run when comparing binary files
--ignore-submodules[=<when>] # Ignore changes to submodules in the diff generation
--src-prefix=<prefix> # Show the given source prefix instead of "a/"
--dst-prefix=<prefix> # Show the given destination prefix instead of "b/"
--no-prefix # Do not show any source or destination prefix
--line-prefix=<prefix> # Prepend an additional prefix to every line of output
--ita-invisible-in-index # By default entries added by "git add -N" appear as an existing empty file in "git diff" and a new file in "git diff --cached"
EXAMPLES
git log --no-merges
Show the whole commit history, but skip any merges
git log v2.6.12.. include/scsi drivers/scsi
Show all commits since version v2.6.12 that changed any file in the include/scsi or drivers/scsi subdirectories
git log --since="2 weeks ago" -- gitk
Show the changes during the last two weeks to the file gitk. The -- is necessary to avoid confusion with the branch named gitk
git log --name-status release..test
Show the commits that are in the "test" branch but not yet in the "release" branch, along with the list of paths each commit modifies
git log --follow builtin/rev-list.c
Shows the commits that changed builtin/rev-list.c, including those commits that occurred before the file was given its present name
git log --branches --not --remotes=origin
Shows all commits that are in any of local branches but not in any of remote-tracking branches for origin (what you have that origin doesn’t)
git log master --not --remotes=*/master
Shows all commits that are in local master but not in any remote repository master branches
git log -p -m --first-parent
Shows the history including change diffs, but only from the “main branch” perspective, skipping commits that come from merged branches, and showing full diffs of changes introduced by the merges. This makes sense only when following
a strict policy of merging all topic branches when staying on a single integration branch
git log -L '/int main/',/^}/:main.c
Shows how the function main() in the file main.c evolved over time
git log -3
Limits the number of commits to show to 3
TRICK
# show all logs
git log
-p -2 # show diff between two last commit
-U1 --word-diff # show diff in line
--stat # show statistics
--pretty=oneline
--pretty=short
--pretty=full
--pretty=fuller
--pretty=format:"%h - %an, %ar : %s"
https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging
Join two or more development histories together
Incorporates changes from the named commits (since the time their histories diverged from the current branch) into the current branch. This command is used by git pull to incorporate changes from another repository and can be used by hand to merge changes from one branch into another
git merge [-n] [--stat] [--no-commit] [--squash] [--[no-]edit] [--no-verify] [-s <strategy>] [-X <strategy-option>] [-S[<keyid>]] [--[no-]allow-unrelated-histories] [--[no-]rerere-autoupdate] [-m <msg>] [-F <file>] [<commit>...]
git merge (--continue | --abort | --quit)
--commit # Perform the merge and commit the result
--no-commit # perform the merge and stop just before creating a merge commit, to give the user a chance to inspect and further tweak the merge result before committing
--edit, -e # Invoke an editor before committing successful mechanical merge to further edit the auto-generated merge message, so that the user can explain and justify the merge
--no-edit # Accept the auto-generated message (this is generally discouraged)
--cleanup=<mode> # Determines how the merge message will be cleaned up before committing
--ff, --no-ff, --ff-only # Specifies how a merge is handled when the merged-in history is already a descendant of the current history
- --ff # is the default unless merging an annotated (and possibly signed) tag that is not stored in its natural place in the refs/tags/ hierarchy, in which case --no-ff is assumed
--no-ff # create a merge commit in all cases, even when the merge could instead be resolved as a fast-forward
--ff-only # resolve the merge as a fast-forward when possible. When not possible, refuse to merge and exit with a non-zero status
-S[<keyid>], --gpg-sign[=<keyid>] # GPG-sign the resulting merge commit. The keyid argument is optional and defaults to the committer identity
--log[=<n>], --no-log # In addition to branch names, populate the log message with one-line descriptions from at most <n> actual commits that are being merged
--no-log # do not list one-line descriptions from the actual commits being merged
--signoff, --no-signoff # Add Signed-off-by line by the committer at the end of the commit log message
--stat # Show a diffstat at the end of the merge
-n, --no-stat # do not show a diffstat at the end of the merge
--squash # produce the working tree and index state as if a real merge happened
--no-squash # perform the merge and commit the result
--verify-signatures, --no-verify-signatures # verify that the tip commit of the side branch being merged is signed with a valid key
-q, --quiet # Operate quietly. Implies --no-progress
-v, --verbose # be verbose
--progress, --no-progress # Turn progress on/off explicitly
--allow-unrelated-histories # by default, git merge command refuses to merge histories that do not share a common ancestor
-m <msg> # set the commit message to be used for the merge commit (in case one is created)
--continue # after a git merge stops due to conflicts you can conclude the merge by running git merge --continue
-s <strategy>, --strategy=<strategy> # use the given merge strategy
- resolve # this can only resolve two heads
recursive # this can only resolve two heads using a 3-way merge algorithm
- options:
ours # forces conflicting hunks to be auto-resolved cleanly by favoring our version
theirs # opposite of ours; note that, unlike ours, there is no theirs merge strategy to confuse this merge option with
patience # merge-recursive spends a little extra time to avoid mismerges that sometimes occur due to unimportant matching lines
diff-algorithm=[patience|minimal|histogram|myers] # use a different diff algorithm, which can help avoid mismerges that occur due to unimportant matching lines
ignore-space-change #
ignore-all-space
ignore-space-at-eol
ignore-cr-at-eol
renormalize # runs a virtual check-out and check-in of all three stages of a file when resolving a three-way merge
no-renormalize # disables the renormalize option
no-renames # turn off rename detection
find-renames[=<n>] # turn on rename detection, optionally setting the similarity threshold
subtree[=<path>] # is a more advanced form of subtree strategy, where the strategy makes a guess on how two trees must be shifted to match with each other when merging
octopus # resolves cases with more than two heads, but refuses to do a complex merge that needs manual resolution
ours # resolves any number of heads, but the resulting tree of the merge is always that of the current branch head, effectively ignoring all changes from all other branches
subtree # This is a modified recursive strategy. When merging trees A and B, if B corresponds to a subtree of A, B is first adjusted to match the tree structure of A, instead of reading the trees at the samelevel
Switch branches or restore working tree files
# To prepare for working on <branch>, switch to it by updating the index and the files in the working tree, and by pointing HEAD at the branch
git checkout [<branch>]
#Specifying -b causes a new branch to be created as if git-branch(1) were called and then checked out
git checkout -b|-B <new_branch> [<start point>]
# Prepare to work on top of <commit>, by detaching HEAD at it (see "DETACHED HEAD" section), and updating the index and the files in the working tree
git checkout --detach [<branch>], git checkout [--detach] <commit>
# Overwrite the contents of the files that match the pathspec. When the <tree-ish> (most often a commit) is not given, overwrite working tree with the contents in the index
git checkout [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] [--] <pathspec>..., git checkout [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] --pathspec-from-file=<file> [--pathspec-file-nul]
# similar to the previous mode, but lets you use the interactive interface to show the "diff" output and choose which hunks to use in the result
git checkout (-p|--patch) [<tree-ish>] [--] [<pathspec>...]
-q, --quiet # Quiet, suppress feedback messages
--progress, --no-progress # Progress status is reported on the standard error stream by default when it is attached to a terminal, unless --quiet is specified
-f, --force # When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes
--ours, --theirs # When checking out paths from the index, check out stage #2 (ours) or #3 (theirs) for unmerged paths
-b <new_branch> # Create a new branch named <new_branch> and start it at <start_point>
-B <new_branch> # Creates the branch <new_branch> and start it at <start_point>; if it already exists, then reset it to <start_point>. This is equivalent to running "git branch" with "-f"
-t, --track # When creating a new branch, set up "upstream" configuration. See "--track" in git-branch(1) for details. If no -b option is given, the name of the new branch will be derived from the remote-tracking branch, by looking at the local part of the refspec configured for the corresponding remote, and then stripping the initial part up to the "*"
--no-track # Do not set up "upstream" configuration, even if the branch.autoSetupMerge configuration variable is true
--guess, --no-guess # If <branch> is not found but there does exist a tracking branch in exactly one remote (call it <remote>) with a matching name, treat as equivalent to $ git checkout -b <branch> --track <remote>/<branch>
-l # Create the new branch’s reflog
--detach # Rather than checking out a branch to work on it, check out a commit for inspection and discardable experiments
--orphan <new_branch> # Create a new orphan branch, named <new_branch>, started from <start_point> and switch to it
--ignore-skip-worktree-bits # In sparse checkout mode, git checkout -- <paths> would update only entries matched by <paths> and sparse patterns in $GIT_DIR/info/sparse-checkout
-m, --merge # a three-way merge between the current branch, your working tree contents, and the new branch is done, and you will be on the new branch
--conflict=<style> # The same as --merge option above, but changes the way the conflicting hunks are presented, overriding the merge.conflictStyle configuration variable
-p, --patch # Interactively select hunks in the difference between the <tree-ish> (or the index, if unspecified) and the working tree
--ignore-other-worktrees # git checkout refuses when the wanted ref is already checked out by another worktree. This option makes it check the ref out anyway. In other words, the ref can be held by more than one worktree
--overwrite-ignore, --no-overwrite-ignore # Silently overwrite ignored files when switching branches. This is the default behavior. Use --no-overwrite-ignore to abort the operation when the new branch contains ignored files
--recurse-submodules, --no-recurse-submodules # Using --recurse-submodules will update the content of all initialized submodules according to the commit recorded in the superproject
--overlay, --no-overlay # In the default overlay mode, git checkout never removes files from the index or the working tree
--pathspec-from-file=<file> # Pathspec is passed in <file> instead of commandline args
--pathspec-file-nul # Only meaningful with --pathspec-from-file. Pathspec elements are separated with NUL character and all other characters are taken literally (including newlines and quotes)
<branch> # Branch to checkout; if it refers to a branch (i.e., a name that, when prepended with "refs/heads/", is a valid ref), then that branch is checked out. Otherwise, if it refers to a valid commit, your HEAD becomes "detached" and you are no longer on any branch
<new_branch> # Name for the new branch
<start_point> # The name of a commit at which to start the new branch. Defaults to HEAD
<tree-ish> # Tree to checkout from (when paths are given). If not specified, the index will be used
-- # Do not interpret any more arguments as options
<pathspec>... # Limits the paths affected by the operation
USED
checkout a remote branch
In order to checkout a remote branch you have to first fetch the contents of the branch
git fetch --all
# or
# git fetch <repo> <branch>
Checkout the remote branch
# In modern versions of Git, you can then checkout the remote branch like a local branch
git checkout <remotebranch>
# Older versions of Git require the creation of a new branch based on the remote
git checkout <remotebranch> <repo>/<remotebranch>
Checkout the local branch
# Additionally you can checkout a new local branch and reset it to the remote branches last commit
git checkout -b <branch> && git reset --hard origin/<branch>
List, create, or delete branches
If --list is given, or if there are no non-option arguments, existing branches are listed; the current branch will be highlighted in green and marked with an asterisk. Any branches checked out in linked worktrees will be highlighted in cyan and marked with a plus sign. Option -r causes the remote-tracking branches to be listed, and option -a shows both local and remote branches
If a <pattern> is given, it is used as a shell wildcard to restrict the output to matching branches. If multiple patterns are given, a branch is shown if it matches any of the patterns
git branch [--color[=<when>] | --no-color] [--show-current] [-v [--abbrev=<length> | --no-abbrev]] [--column[=<options>] | --no-column] [--sort=<key>] [(--merged | --no-merged) [<commit>]] [--contains [<commit]] [--no-contains [<commit>]] [--points-at <object>] [--format=<format>] [(-r | --remotes) | (-a | --all)] [--list] [<pattern>...]
git branch [--track | --no-track] [-f] <branchname> [<start-point>]
git branch (--set-upstream-to=<upstream> | -u <upstream>) [<branchname>]
git branch --unset-upstream [<branchname>]
git branch (-m | -M) [<oldbranch>] <newbranch>
git branch (-c | -C) [<oldbranch>] <newbranch>
git branch (-d | -D) [-r] <branchname>...
git branch --edit-description [<branchname>]
-d, --delete # Delete a branch. The branch must be fully merged in its upstream branch, or in HEAD if no upstream was set with --track or --set-upstream-to
-D # Shortcut for --delete --force
--create-reflog # Create the branch’s reflog. This activates recording of all changes made to the branch ref, enabling use of date based sha1 expressions such as "<branchname>@{yesterday}"
-f, --force # Reset <branchname> to <startpoint>, even if <branchname> exists already. Without -f, git branch refuses to change an existing branch. In combination with -d (or --delete), allow deleting the branch irrespective of its merged status. In combination with -m (or --move), allow renaming the branch even if the new branch name already exists, the same applies for -c (or --copy)
-m, --move # Move/rename a branch and the corresponding reflog
-M # Shortcut for --move --force
-c, --copy # Copy a branch and the corresponding reflog
-C # Shortcut for --copy --force
--color[=<when>] # Color branches to highlight current, local, and remote-tracking branches. The value must be always (the default), never, or auto
--no-color # Turn off branch colors, even when the configuration file gives the default to color output. Same as --color=never
-i, --ignore-case # Sorting and filtering branches are case insensitive
--column[=<options>], --no-column # Display branch listing in columns. See configuration variable column.branch for option syntax
-r, --remotes # List or delete (if used with -d) the remote-tracking branches. Combine with --list to match the optional pattern(s)
-a, --all # List both remote-tracking branches and local branches. Combine with --list to match optional pattern(s)
-l, --list # List branches. With optional <pattern>..., e.g. git branch --list 'maint-*', list only the branches that match the pattern(s)
--show-current # Print the name of the current branch. In detached HEAD state, nothing is printed
-v, -vv, --verbose # When in list mode, show sha1 and commit subject line for each head, along with relationship to upstream branch (if any)
-q, --quiet # Be more quiet when creating or deleting a branch, suppressing non-error messages
--abbrev=<length> # Alter the sha1’s minimum display length in the output listing. The default value is 7 and can be overridden by the core.abbrev config option
--no-abbrev # Display the full sha1s in the output listing rather than abbreviating them
-t, --track # When creating a new branch, set up branch.<name>.remote and branch.<name>.merge configuration entries to mark the start-point branch as "upstream" from the new branch
--no-track # Do not set up "upstream" configuration, even if the branch.autoSetupMerge configuration variable is true
-u <upstream>, --set-upstream-to=<upstream> # Set up <branchname>'s tracking information so <upstream> is considered <branchname>'s upstream branch. If no <branchname> is specified, then it defaults to the current branch
--unset-upstream # Remove the upstream information for <branchname>. If no branch is specified it defaults to the current branch
--edit-description # Open an editor and edit the text to explain what the branch is for, to be used by various other commands (e.g. format-patch, request-pull, and merge (if enabled)). Multi-line explanations may be used
--contains [<commit>] # Only list branches which contain the specified commit (HEAD if not specified). Implies --list
--no-contains [<commit>] # Only list branches which don’t contain the specified commit (HEAD if not specified). Implies --list
--merged [<commit>] # Only list branches whose tips are reachable from the specified commit (HEAD if not specified). Implies --list, incompatible with --no-merged
--no-merged [<commit>] # Only list branches whose tips are not reachable from the specified commit (HEAD if not specified). Implies --list, incompatible with --merged
<branchname> # The name of the branch to create or delete. The new branch name must pass all checks defined by git-check-ref-format(1). Some of these checks may restrict the characters allowed in a branch name
<start-point> # The new branch head will point to this commit. It may be given as a branch name, a commit-id, or a tag. If this option is omitted, the current HEAD will be used instead
<oldbranch> # The name of an existing branch to rename
<newbranch> # The new name for an existing branch. The same restrictions as for <branchname> apply
--sort=<key> # Sort based on the key given. Prefix - to sort in descending order of the value. You may use the --sort=<key> option multiple times, in which case the last key becomes the primary key
--points-at <object> # Only list branches of the given object
--format <format> # A string that interpolates %(fieldname) from a branch ref being shown and the object it points at. The format is the same as that of git-for-each-ref(1)
Show changes between commits, commit and working tree, etc
Show changes between the working tree and the index or a tree, changes between the index and a tree, changes between two trees, changes between two blob objects, or changes between two files on disk
# view the changes you made relative to the index (staging area for the next commit)
git diff [<options>] [--] [<path>...]
# compare the given two paths on the filesystem
git diff [<options>] --no-index [--] <path> <path>
# view the changes you staged for the next commit relative to the named <commit>
git diff [<options>] --cached [<commit>] [--] [<path>...]
# view the changes you have in your working tree relative to the named <commit>
git diff [<options>] <commit> [--] [<path>...]
# view the changes between two arbitrary <commit>
git diff [<options>] <commit> <commit> [--] [<path>...]
git diff [<options>] <commit>..<commit> [--] [<path>...]
# view the changes on the branch containing and up to the second <commit>, starting at a common ancestor of both <commit>
git diff [<options>] <commit>...<commit> [--] [<path>...]
-p, -u, --patch # Generate patch (see section on generating patches). This is the default
-s, --no-patch # Suppress diff output. Useful for commands like git show that show the patch by default, or to cancel the effect of --patch
-U<n>, --unified=<n> # Generate diffs with <n> lines of context instead of the usual three. Implies --patch. Implies -p
--output=<file> # Output to a specific file instead of stdout
--output-indicator-new=<char>, --output-indicator-old=<char>, --output-indicator-context=<char> # Specify the character used to indicate new, old or context lines in the generated patch. Normally they are +, - and ' ' respectively
--raw # Generate the diff in raw format
--patch-with-raw # Synonym for -p --raw
--indent-heuristic # Enable the heuristic that shifts diff hunk boundaries to make patches easier to read. This is the default
--no-indent-heuristic # Disable the indent heuristic
--minimal # Spend extra time to make sure the smallest possible diff is produced
--patience # Generate a diff using the "patience diff" algorithm
--histogram # Generate a diff using the "histogram diff" algorithm
--anchored=<text> # Generate a diff using the "anchored diff" algorithm
--diff-algorithm={patience|minimal|histogram|myers} # Choose a diff algorithm. The variants are as follows:
default, myers # The basic greedy diff algorithm. Currently, this is the default
minimal # Spend extra time to make sure the smallest possible diff is produced
patience # Use "patience diff" algorithm when generating patches
histogram # This algorithm extends the patience algorithm to "support low-occurrence common elements"
--stat[=<width>[,<name-width>[,<count>]]] # Generate a diffstat
--compact-summary # Output a condensed summary of extended header information such as file creations or deletions ("new" or "gone", optionally "+l" if it’s a symlink) and mode changes ("+x" or "-x" for adding or removing executable bit respectively) in diffstat
--numstat # Similar to --stat, but shows number of added and deleted lines in decimal notation and pathname without abbreviation, to make it more machine friendly
--shortstat # Output only the last line of the --stat format containing total number of modified files, as well as number of added and deleted lines
-X[<param1,param2,...>], --dirstat[=<param1,param2,...>] # Output the distribution of relative amount of changes for each sub-directory. The behavior of --dirstat can be customized by passing it a comma separated list of parameters. The following parameters are available:
changes # # Compute the dirstat numbers by counting the lines that have been removed from the source, or added to the destination
lines # Compute the dirstat numbers by doing the regular line-based diff analysis, and summing the removed/added line counts
files # Compute the dirstat numbers by counting the number of files changed. Each changed file counts equally in the dirstat analysis
cumulative # Count changes in a child directory for the parent directory as well
<limit> # An integer parameter specifies a cut-off percent (3% by default)
--dirstat-by-file[=<param1,param2>...] # Synonym for --dirstat=files,param1,param2...
--summary # Output a condensed summary of extended header information such as creations, renames and mode changes
--patch-with-stat # Synonym for -p --stat
-z # When --raw, --numstat, --name-only or --name-status has been given, do not munge pathnames and use NULs as output field terminators
--name-only # Show only names of changed files
--name-status # Show only names and status of changed files. See the description of the --diff-filter option on what the status letters mean
--submodule[=<format>] # Specify how differences in submodules are shown. When specifying --submodule=short the short format is used
--color[=<when>] # Show colored diff. --color (i.e. without =<when>) is the same as --color=always
--no-color # Turn off colored diff. This can be used to override configuration settings. It is the same as --color=never
--color-moved[=<mode>] # Moved lines of code are colored differently. <mode> defaults to no. The mode must be one of:
no # Moved lines are not highlighted
default # Is a synonym for zebra. This may change to a more sensible mode in the future
plain # Any line that is added in one location and was removed in another location will be colored with color.diff.newMoved
blocks # Blocks of moved text of at least 20 alphanumeric characters are detected greedily
zebra # Blocks of moved text are detected as in blocks mode
dimmed-zebra # Similar to zebra, but additional dimming of uninteresting parts of moved code is performed
--no-color-moved-ws # Do not ignore whitespace when performing move detection. This can be used to override configuration settings
--word-diff[=<mode>] # Show a word diff, using the <mode> to delimit changed words. The <mode> defaults to plain, and must be one of:
color # Highlight changed words using only colors. Implies --color
plain # Show words as [-removed-] and {+added+}
porcelain # Use a special line-based format intended for script consumption
none # Disable word diff again
--word-diff-regex=<regex> # Use <regex> to decide what a word is, instead of considering runs of non-whitespace to be a word
--color-words[=<regex>] # Equivalent to --word-diff=color plus (if a regex was specified) --word-diff-regex=<regex>
--no-renames # Turn off rename detection, even when the configuration file gives the default to do so
--[no-]rename-empty # Whether to use empty blobs as rename source
--check # Warn if changes introduce conflict markers or whitespace errors. What are considered whitespace errors is controlled by core
--ws-error-highlight=<kind> # Highlight whitespace errors in the context, old or new lines of the diff
--full-index # Instead of the first handful of characters, show the full pre- and post-image blob object names on the "index" line when generating patch format output
--binary # In addition to --full-index, output a binary diff that can be applied with git-apply. Implies --patch
--abbrev[=<n>] # Instead of showing the full 40-byte hexadecimal object name in diff-raw format output and diff-tree header lines, show only a partial prefix
-B[<n>][/<m>], --break-rewrites[=[<n>][/<m>]] # Break complete rewrite changes into pairs of delete and create
-M[<n>], --find-renames[=<n>] # Detect renames. If n is specified, it is a threshold on the similarity index (i.e. amount of addition/deletions compared to the file’s size)
-C[<n>], --find-copies[=<n>] # Detect copies as well as renames
--find-copies-harder # For performance reasons, by default, -C option finds copies only if the original file of the copy was modified in the same changeset
-D, --irreversible-delete # Omit the preimage for deletes, i.e. print only the header but not the diff between the preimage and /dev/null
-l<num> # The -M and -C options require O(n^2) processing time where n is the number of potential rename/copy targets
--diff-filter=[(A|C|D|M|R|T|U|X|B)...[*]] # Select only files that are Added (A), Copied (C), Deleted (D), Modified (M), Renamed (R), have their type (i.e. regular file, symlink, submodule, ...) changed (T), are Unmerged (U), are Unknown (X), or have had their pairing Broken (B)
-S<string> # Look for differences that change the number of occurrences of the specified string (i.e. addition/deletion) in a file
-G<regex> # Look for differences whose patch text contains added/removed lines that match <regex>
--find-object=<object-id> # Look for differences that change the number of occurrences of the specified object
--pickaxe-all # When -S or -G finds a change, show all the changes in that changeset, not just the files that contain the change in <string>
--pickaxe-regex # Treat the <string> given to -S as an extended POSIX regular expression to match
-O<orderfile> # Control the order in which files appear in the output. <orderfile> is parsed as follows:
- Blank lines are ignored, so they can be used as separators for readability
- Lines starting with a hash ("#") are ignored, so they can be used for comments. Add a backslash ("\\") to the beginning of the pattern if it starts with a hash
- Each other line contains a single pattern
-R # Swap two inputs; that is, show differences from index or on-disk file to tree contents
--relative[=<path>] # When run from a subdirectory of the project, it can be told to exclude changes outside the directory and show pathnames relative to it with this option
-a, --text # Treat all files as text
--ignore-cr-at-eol # Ignore carriage-return at the end of line when doing a comparison
--ignore-space-at-eol # Ignore changes in whitespace at EOL
--ignore-space-at-eol # Ignore changes in whitespace at EOL
-b, --ignore-space-change # Ignore changes in amount of whitespace
-w, --ignore-all-space # Ignore whitespace when comparing lines
--ignore-blank-lines # Ignore changes whose lines are all blank
--inter-hunk-context=<lines> # Show the context between diff hunks, up to the specified number of lines, thereby fusing hunks that are close to each other
-W, --function-context # Show whole surrounding functions of changes
--exit-code # Make the program exit with codes similar to diff(1). That is, it exits with 1 if there were differences and 0 means no differences
--quiet # Disable all output of the program. Implies --exit-code
--ext-diff # Allow an external diff helper to be executed. If you set an external diff driver with gitattributes(5), you need to use this option with git-log(1) and friends
--no-ext-diff # Disallow external diff drivers
--textconv, --no-textconv # Allow (or disallow) external text conversion filters to be run when comparing binary files
--ignore-submodules[=<when>] # Ignore changes to submodules in the diff generation
--src-prefix=<prefix> # Show the given source prefix instead of "a/"
--dst-prefix=<prefix> # Show the given destination prefix instead of "b/"
--no-prefix # Do not show any source or destination prefix
--line-prefix=<prefix> # Prepend an additional prefix to every line of output
--ita-invisible-in-index # By default entries added by "git add -N" appear as an existing empty file in "git diff" and a new file in "git diff --cached"
-1 --base, -2 --ours, -3 --theirs # Compare the working tree with the "base" version (stage #1), "our branch" (stage #2) or "their branch" (stage #3)
-0 # Omit diff output for unmerged entries and just show "Unmerged". Can be used only when comparing the working tree with the index
<path>... # The <paths> parameters, when given, are used to limit the diff to the named paths (you can give directory names and get diff for all files under them)
USED
# show diff staged / repo
git diff --staged
Move or rename a file, a directory, or a symlink
# renames <source>
git mv [-v] [-f] [-n] [-k] <source> <destination>
# the last argument has to be an existing directory; the given sources will be moved into this directory
git mv [-v] [-f] [-n] [-k] <source> ... <destination directory>
-f, --force # Force renaming or moving of a file even if the target exists
-k # Skip move or rename actions which would lead to an error condition. An error happens when a source is neither existing nor controlled by Git, or when it would overwrite an existing file unless -f is given.
-n, --dry-run # Do nothing; only show what would happen
-v, --verbose # Report the names of files as they are moved.
Remove files from the working tree and from the index
Remove files from the index, or from the working tree and the index. git rm will not remove a file from just your working directory. (There is no option to remove a file only from the working tree and yet keep it in the index; use /bin/rm if you want to do that.) The files being removed have to be identical to the tip of the branch, and no updates to their contents can be staged in the index, though that default behavior can be overridden with the -f option. When --cached is given, the staged content has to match either the tip of the branch or the file on disk, allowing the file to be removed from just the index
git rm [-f | --force] [-n] [-r] [--cached] [--ignore-unmatch] [--quiet] [--] <file>...
<file>... # Files to remove. Fileglobs (e.g. *.c) can be given to remove all matching files. If you want Git to expand file glob characters, you may need to shell-escape them
-f, --force # Override the up-to-date check
-n, --dry-run # Don’t actually remove any file(s). Instead, just show if they exist in the index and would otherwise be removed by the command
-r # Allow recursive removal when a leading directory name is given
-- # This option can be used to separate command-line options from the list of files, (useful when filenames might be mistaken for command-line options)
--cached # Use this option to unstage and remove paths only from the index. Working tree files, whether modified or not, will be left alone
--ignore-unmatch # Exit with a zero status even if no files matched
-q, --quiet # git rm normally outputs one line (in the form of an rm command) for each file removed. This option suppresses that output
Reset current HEAD to the specified state
In the first three forms, copy entries from <tree-ish> to the index. In the last form, set the current branch head (HEAD) to <commit>, optionally modifying index and working tree to match. The <tree-ish>/<commit> defaults to HEAD in all forms
# These forms reset the index entries for all paths that match the <pathspec> to their state at <tree-ish>
git reset [-q] [<tree-ish>] [--] <pathspec>..., git reset [-q] [--pathspec-from-file=<file> [--pathspec-file-nul]] [<tree-ish>]
# Interactively select hunks in the difference between the index and <tree-ish> (defaults to HEAD). The chosen hunks are applied in reverse to the index. This means that git reset -p is the opposite of git add -p
git reset (--patch | -p) [<tree-ish>] [--] [<pathspec>...]
# This form resets the current branch head to <commit> and possibly updates the index (resetting it to the tree of <commit>) and the working tree depending on <mode>
git reset [<mode>] [<commit>]
--soft # Does not touch the index file or the working tree at all (but resets the head to <commit>, just like all modes do)
--mixed # Resets the index but not the working tree (i.e., the changed files are preserved but not marked for commit) and reports what has not been updated
--hard # Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded
--merge # Resets the index and updates the files in the working tree that are different between <commit> and HEAD, but keeps those which are different between the index and working tree (i.e. which have changes which have not been added)
--keep # Resets index entries and updates files in the working tree that are different between <commit> and HEAD
-q, --quiet, --no-quiet # Be quiet, only report errors. The default behavior is set by the reset.quiet config option. --quiet and --no-quiet will override the default behavior
--pathspec-from-file=<file> # Pathspec is passed in <file> instead of commandline args. If <file> is exactly - then standard input is used
--pathspec-file-nul # Only meaningful with --pathspec-from-file. Pathspec elements are separated with NUL character and all other characters are taken literally (including newlines and quotes)
-- # Do not interpret any more arguments as options
<pathspec>... # Limits the paths affected by the operation
Add file contents to the index
This command updates the index using the current content found in the working tree, to prepare the content staged for the next commit. It typically adds the current content of existing paths as a whole, but with some options it can also be used to add content with only part of the changes made to the working tree files applied, or remove paths that do not exist in the working tree anymore
git add [--verbose | -v] [--dry-run | -n] [--force | -f] [--interactive | -i] [--patch | -p] [--edit | -e] [--[no-]all | --[no-]ignore-removal | [--update | -u]] [--intent-to-add | -N] [--refresh] [--ignore-errors] [--ignore-missing] [--renormalize] [--chmod=(+|-)x] [--pathspec-from-file=<file> [--pathspec-file-nul]] [--] [<pathspec>...]
<pathspec>... # Files to add content from. Fileglobs (e.g. *.c) can be given to add all matching files
-n, --dry-run # Don’t actually add the file(s), just show if they exist and/or will be ignored
-v, --verbose # Be verbose
-f, --force # Allow adding otherwise ignored files
-i, --interactive # Add modified contents in the working tree interactively to the index. Optional path arguments may be supplied to limit operation to a subset of the working tree
-p, --patch # Interactively choose hunks of patch between the index and the work tree and add them to the index
-e, --edit # Open the diff vs. the index in an editor and let the user edit it
-u, --update # Update the index just where it already has an entry matching <pathspec>
-A, --all, --no-ignore-removal # Update the index not only where the working tree has a file matching <pathspec> but also where the index already has an entry
--no-all, --ignore-removal # Update the index by adding new files that are unknown to the index and files modified in the working tree, but ignore files that have been removed from the working tree
-N, --intent-to-add # Record only the fact that the path will be added later. An entry for the path is placed in the index with no content
--refresh # Don’t add the file(s), but only refresh their stat() information in the index
--ignore-errors # If some files could not be added because of errors indexing them, do not abort the operation, but continue adding the others
--ignore-missing # This option can only be used together with --dry-run
--no-warn-embedded-repo # By default, git add will warn when adding an embedded repository to the index without using git submodule add to create an entry in .gitmodules
--renormalize # Apply the "clean" process freshly to all tracked files to forcibly add them again to the index
--chmod=(+|-)x # Override the executable bit of the added files
--pathspec-from-file=<file> # Pathspec is passed in <file> instead of commandline args
--pathspec-file-nul # Only meaningful with --pathspec-from-file
-- # This option can be used to separate command-line options from the list of files, (useful when filenames might be mistaken for command-line options)
https://chris.beams.io/posts/git-commit/
Record changes to the repository
Create a new commit containing the current contents of the index and the given log message describing the changes. The new commit is a direct child of HEAD, usually the tip of the current branch, and the branch is updated to point to it (unless no branch is associated with the working tree, in which case HEAD is "detached" as described in git-checkout(1))
git commit [-a | --interactive | --patch] [-s] [-v] [-u<mode>] [--amend] [--dry-run] [(-c | -C | --fixup | --squash) <commit>] [-F <file> | -m <msg>] [--reset-author] [--allow-empty] [--allow-empty-message] [--no-verify] [-e] [--author=<author>] [--date=<date>] [--cleanup=<mode>] [--[no-]status] [-i | -o] [--pathspec-from-file=<file> [--pathspec-file-nul]] [-S[<keyid>]] [--] [<pathspec>...]
-a, --all # Tell the command to automatically stage files that have been modified and deleted, but new files you have not told Git about are not affected
-p, --patch # Use the interactive patch selection interface to chose which changes to commit. See git-add(1) for details
-C <commit>, --reuse-message=<commit> # Take an existing commit object, and reuse the log message and the authorship information (including the timestamp) when creating the commit
-c <commit>, --reedit-message=<commit> # Like -C, but with -c the editor is invoked, so that the user can further edit the commit message
--fixup=<commit> # Construct a commit message for use with rebase --autosquash
--squash=<commit> # Construct a commit message for use with rebase --autosquash
--reset-author # When used with -C/-c/--amend options, or when committing after a conflicting cherry-pick, declare that the authorship of the resulting commit now belongs to the committer
--short # When doing a dry-run, give the output in the short-format. See git-status(1) for details. Implies --dry-run
--branch # Show the branch and tracking info even in short-format
--porcelain # When doing a dry-run, give the output in a porcelain-ready format. See git-status(1) for details. Implies --dry-run
--long # When doing a dry-run, give the output in the long-format. Implies --dry-run
-z, --null # When showing short or porcelain status output, print the filename verbatim and terminate the entries with NUL, instead of LF
-F <file>, --file=<file> # Take the commit message from the given file. Use - to read the message from the standard input
--author=<author> # Override the commit author
--date=<date> # Override the author date used in the commit
-m <msg>, --message=<msg> # Use the given <msg> as the commit message
-t <file>, --template=<file> # When editing the commit message, start the editor with the contents in the given file
-s, --signoff # Add Signed-off-by line by the committer at the end of the commit log message
-n, --no-verify # This option bypasses the pre-commit and commit-msg hooks
--allow-empty # Usually recording a commit that has the exact same tree as its sole parent commit is a mistake, and the command prevents you from making such a commit
--allow-empty-message # Like --allow-empty this command is primarily for use by foreign SCM interface scripts
--cleanup=<mode> # This option determines how the supplied commit message should be cleaned up before committing. The <mode> can be strip, whitespace, verbatim, scissors or default
strip # Strip leading and trailing empty lines, trailing whitespace, commentary and collapse consecutive empty lines
whitespace # Same as strip except #commentary is not removed
verbatim # Do not change the message at all
scissors # Same as whitespace except that everything from (and including) the line found below is truncated, if the message is to be edited. "#" can be customized with core.commentChar
default # Same as strip if the message is to be edited. Otherwise whitespace
-e, --edit # The message taken from file with -F, command line with -m, and from commit object with -C are usually used as the commit log message unmodified
--no-edit # Use the selected commit message without launching an editor
--amend # Replace the tip of the current branch by creating a new commit
--no-post-rewrite # Bypass the post-rewrite hook
-i, --include # Before making a commit out of staged contents so far, stage the contents of paths given on the command line as well
-o, --only # Make a commit by taking the updated working tree contents of the paths specified on the command line, disregarding any contents that have been staged for other paths
--pathspec-from-file=<file> # Pathspec is passed in <file> instead of commandline args
--pathspec-file-nul # Only meaningful with --pathspec-from-file
-u[<mode>], --untracked-files[=<mode>] # Show untracked files. The mode parameter is optional (defaults to all). The possible options are:
no # Show no untracked files
normal # Shows untracked files and directories
all # Also shows individual files in untracked directories
-v, --verbose # Show unified diff between the HEAD commit and what would be committed at the bottom of the commit message template to help the user describe the commit by reminding what changes the commit has
-q, --quiet # Suppress commit summary message
--dry-run # Do not create a commit, but show a list of paths that are to be committed, paths with local changes that will be left uncommitted and paths that are untracked
--status # Include the output of git-status(1) in the commit message template when using an editor to prepare the commit message
--no-status # Do not include the output of git-status(1) in the commit message template when using an editor to prepare the default commit message
-S[<keyid>], --gpg-sign[=<keyid>] # GPG-sign commits. The keyid argument is optional and defaults to the committer identity; if specified,
--no-gpg-sign # Countermand commit.gpgSign configuration variable that is set to force each and every commit to be signed
-- # Do not interpret any more arguments as options
<pathspec>... # When pathspec is given on the command line, commit the contents of the files that match the pathspec without recording the changes already added to the index
USED
git commit -m "initial version - $(date +%Y-%m-%d)" # commit with message
git commit -a -m "$message" # commit unstaged files in working copy to the repo
SHOW
Show a reference to an object or a list of objects may be passed to examine those specific objects
Shows one or more objects (blobs, trees, tags and commits)
- For commits it shows the log message and textual diff. It also presents the merge commit in a special format as produced by git diff-tree --cc
- For tags, it shows the tag message and the referenced objects
- For trees, it shows the names (equivalent to git ls-tree with --name-only)
- For plain blobs, it shows the plain contents
git show [<options>] [<object>...]
--pretty[=<format>] # displays more or less information depending on the format chosen: oneline, short, medium, full, fuller, email, raw, string. default is medium
--abbrev-commit # shortens the length of output commit IDs. With --pretty=oneline can produce a highly succinct git log output
--no-abbrev-commit # Show the full 40 character commit ID
--oneline # uses the expanded command --pretty=oneline --abbrev-commit
--encoding[=<encoding>] # Character encoding on Git log messages defaults to UTF-8
--expand-tabs=<n> # replace tab characters with <n> spaces in the log message output
--expand-tabs # replace tab characters with 8 default spaces
--no-expand-tabs # replace tab characters with 0 space
--notes=<ref> # filters notes with <ref>
--no-notes # hide notes in output
--show-signature # show signature if commit are signed with gpg key
SHOW-BRANCH
Show branches and their commits
Shows the commit ancestry graph starting from the commits named with <rev>s or <glob>s (or all refs under refs/heads and/or refs/tags) semi-visually
git show-branch [-a|--all] [-r|--remotes] [--topo-order | --date-order] [--current] [--color[=<when>] | --no-color] [--sparse] [--more=<n> | --list | --independent | --merge-base] [--no-name | --sha1-name] [--topics] [(<rev> | <glob>)...]
git show-branch (-g|--reflog)[=<n>[,<base>]] [--list] [<ref>]
<rev> # Arbitrary extended SHA-1 expression (see gitrevisions(7)) that typically names a branch head or a tag
<glob> # A glob pattern that matches branch or tag names under refs/. For example, if you have many topic branches under refs/heads/topic, giving topic/* would show all of them
-r, --remotes # Show the remote-tracking branches
-a, --all # Show both remote-tracking branches and local branches
--current # With this option, the command includes the current branch to the list of revs to be shown when it is not given on the command line
--topo-order # By default, the branches and their commits are shown in reverse chronological order. This option makes them appear in topological order (i.e., descendant commits are shown before their parents)
--date-order # This option is similar to --topo-order in the sense that no parent comes before all of its children, but otherwise commits are ordered according to their commit date
--sparse # By default, the output omits merges that are reachable from only one tip being shown. This option makes them visible
--more=<n> # Usually the command stops output upon showing the commit that is the common ancestor of all the branches. This flag tells the command to go <n> more common commits beyond that
--list # Synonym to --more=-1
--merge-base # Instead of showing the commit list, determine possible merge bases for the specified commits
--independent # Among the <reference>s given, display only the ones that cannot be reached from any other <reference>
--no-name # Do not show naming strings for each commit
--sha1-name # Instead of naming the commits using the path to reach them from heads (e.g. "master~2" to mean the grandparent of "master"), name them with the unique prefix of their object names
--topics # Shows only commits that are NOT on the first branch given. This helps track topic branches by hiding any commit that is already in the main line of development
-g, --reflog[=<n>[,<base>]] [<ref>] # Shows <n> most recent ref-log entries for the given ref. If <base> is given, <n> entries going back from that entry. <base> can be specified as count or date. When no explicit <ref> parameter is given, it defaults to the current branch (or HEAD if it is detached)
--color[=<when>] # Color the status sign (one of these: * ! + -) of each commit corresponding to the branch it’s in
--no-color # Turn off colored output, even when the configuration file gives the default to color output
Show the working tree status
Displays paths that have differences between the index file and the current HEAD commit, paths that have differences between the working tree and the index file, and paths in the working tree that are not tracked by Git
git status [<options>...] [--] [<pathspec>...]
-s, --short # Give the output in the short-format
-b, --branch # Show the branch and tracking info even in short-format
--show-stash # Show the number of entries currently stashed away
--porcelain[=<version>] # Give the output in an easy-to-parse format for scripts. This is similar to the short output, but will remain stable across Git versions and regardless of user configuration
--long # Give the output in the long-format. This is the default
-v, --verbose # In addition to the names of files that have been changed, also show the textual changes that are staged to be committed
-u[<mode>], --untracked-files[=<mode>] # Show untracked files. The possible options are:
no # Show no untracked files
normal # Shows untracked files and directories
all # Also shows individual files in untracked directories
--ignore-submodules[=<when>] # Ignore changes to submodules when looking for changes. <when> can be either "none", "untracked", "dirty" or "all", which is the default
--ignored[=<mode>] # Show ignored files as well. defaults to traditional. The possible options are:
traditional # Shows ignored files and directories, unless --untracked-files=all is specified, in which case individual files in ignored directories are displayed
no # Show no ignored files
matching # Shows ignored files and directories matching an ignore pattern
-z # Terminate entries with NUL, instead of LF. This implies the --porcelain=v1 output format if no other format is given
--column[=<options>], --no-column # Display untracked files in columns. See configuration variable column.status for option syntax.--column and --no-column without options are equivalent to always and never respectively
--ahead-behind, --no-ahead-behind # Display or do not display detailed ahead/behind counts for the branch relative to its upstream branch. Defaults to true
--renames, --no-renames # Turn on/off rename detection regardless of user configuration. See also git-diff(1) --no-renames
--find-renames[=<n>] # Turn on rename detection, optionally setting the similarity threshold. See also git-diff(1) --find-renames
<pathspec>... # See the pathspec entry in gitglossary(7)
Clone a repository into a new directory
Clones a repository into a newly created directory, creates remote-tracking branches for each branch in the cloned repository (visible using git branch --remotes), and creates and checks out an initial branch that is forked from the cloned repository’s currently active branch
The following syntaxes may be used with them:
- ssh://[user@]host.xz[:port]/path/to/repo.git/
- git://host.xz[:port]/path/to/repo.git/
- http[s]://host.xz[:port]/path/to/repo.git/
- ftp[s]://host.xz[:port]/path/to/repo.git/
The ssh and git protocols additionally support ~username expansion:
- ssh://[user@]host.xz[:port]/~[user]/path/to/repo.git/
- git://host.xz[:port]/~[user]/path/to/repo.git/
- [user@]host.xz:/~[user]/path/to/repo.git/
For local repositories, the following syntaxes may be used:
- /path/to/repo.git/
- file:///path/to/repo.git/
git clone [--template=<template_directory>] [-l] [-s] [--no-hardlinks] [-q] [-n] [--bare] [--mirror] [-o <name>] [-b <name>] [-u <upload-pack>] [--reference <repository>] [--dissociate] [--separate-git-dir <git dir>] [--depth <depth>] [--[no-]single-branch] [--no-tags] [--recurse-submodules[=<pathspec>]] [--[no-]shallow-submodules] [--[no-]remote-submodules] [--jobs <n>] [--sparse] [--] <repository> [<directory>]
-l, --local # When the repository to clone from is on a local machine, this flag bypasses the normal "Git aware" transport mechanism and clones the repository by making a copy of HEAD and everything under objects and refs directories
--no-hardlinks # Force the cloning process from a repository on a local filesystem to copy the files under the .git/objects directory instead of using hardlinks. This may be desirable if you are trying to make a back-up of your repository
-s, --shared # When the repository to clone is on the local machine, instead of using hard links, automatically setup .git/objects/info/alternates to share the objects with the source repository
--reference[-if-able] <repository> # If the reference repository is on the local machine, automatically setup .git/objects/info/alternates to obtain objects from the reference repository
--dissociate # Borrow the objects from reference repositories specified with the --reference options only to reduce network transfer, and stop borrowing from them after a clone is made by making necessary local copies of borrowed objects
-q, --quiet # Operate quietly. Progress is not reported to the standard error stream
-v, --verbose # Run verbosely. Does not affect the reporting of progress status to the standard error stream
--progress # Progress status is reported on the standard error stream by default when it is attached to a terminal, unless --quiet is specified. This flag forces progress status even if the standard error stream is not directed to a terminal
--server-option=<option> # Transmit the given string to the server when communicating using protocol version 2. The given string must not contain a NUL or LF character
-n, --no-checkout # No checkout of HEAD is performed after the clone is complete
--bare # Make a bare Git repository. That is, instead of creating <directory> and placing the administrative files in <directory>/.git, make the <directory> itself the $GIT_DIR
--sparse # Initialize the sparse-checkout file so the working directory starts with only the files in the root of the repository. The sparse-checkout file can be modified to grow the working directory as needed
--mirror # Set up a mirror of the source repository
-o <name>, --origin <name> # Instead of using the remote name origin to keep track of the upstream repository, use <name>
-b <name>, --branch <name> # Instead of pointing the newly created HEAD to the branch pointed to by the cloned repository’s HEAD, point to <name> branch instead
-u <upload-pack>, --upload-pack <upload-pack> # When given, and the repository to clone from is accessed via ssh, this specifies a non-default path for the command run on the other end
--template=<template_directory> # Specify the directory from which templates will be used; (See the "TEMPLATE DIRECTORY" section of git-init(1).)
-c <key>=<value>, --config <key>=<value> # Set a configuration variable in the newly-created repository; this takes effect immediately after the repository is initialized, but before the remote history is fetched or any files checked out
--depth <depth> # Create a shallow clone with a history truncated to the specified number of commits
--shallow-since=<date> # Create a shallow clone with a history after the specified time
--shallow-exclude=<revision> # Create a shallow clone with a history, excluding commits reachable from a specified remote branch or tag. This option can be specified multiple times
--[no-]single-branch # Clone only the history leading to the tip of a single branch, either specified by the --branch option or the primary branch remote’s HEAD points at. Further fetches into the resulting repository will only update the remote-tracking branch for the branch this option was used for the initial cloning. If the HEAD at the remote did not point at any branch when --single-branch clone was made, no remote-tracking branch is created
--no-tags # Don’t clone any tags, and set remote.<remote>.tagOpt=--no-tags in the config, ensuring that future git pull and git fetch operations won’t follow any tags
--recurse-submodules[=<pathspec] # After the clone is created, initialize and clone submodules within based on the provided pathspec
--[no-]shallow-submodules # All submodules which are cloned will be shallow with a depth of 1
--[no-]remote-submodules # All submodules which are cloned will use the status of the submodule’s remote-tracking branch to update the submodule, rather than the superproject’s recorded SHA-1. Equivalent to passing --remote to git submodule update
--separate-git-dir=<git dir> # Instead of placing the cloned repository where it is supposed to be, place the cloned repository at the specified directory, then make a filesystem-agnostic Git symbolic link to there
-j <n>, --jobs <n> # The number of submodules fetched at the same time. Defaults to the submodule.fetchJobs option
<repository> # The (possibly remote) repository to clone from. See the GIT URLS section below for more information on specifying repositories
<directory> # The name of a new directory to clone into. The "humanish" part of the source repository is used if no directory is explicitly given (repo for /path/to/repo.git and foo for host.xz:foo/.git)
USED
git://$urlrepo # clone a repository
git://$urlrepo <alias> # clone a repository & give it an alias
Create an empty Git repository or reinitialize an existing one
This command creates an empty Git repository - basically a .git directory with subdirectories for objects, refs/heads, refs/tags, and template files. An initial HEAD file that references the HEAD of the master branch is also created
git init [-q | --quiet] [--bare] [--template=<template_directory>] [--separate-git-dir <git dir>] [--shared[=<permissions>]] [directory]
-q, --quiet # Only print error and warning messages; all other output will be suppressed
--bare # Create a bare repository. If GIT_DIR environment is not set, it is set to the current working directory
--template=<template_directory> # Specify the directory from which templates will be used
--separate-git-dir=<git dir> # Instead of initializing the repository as a directory to either $GIT_DIR or ./.git/, create a text file there containing the path to the actual repository
--shared[=(false|true|umask|group|all|world|everybody|0xxx)] # Specify that the Git repository is to be shared amongst several users
Get and set repository or global options
You can query/set/replace/unset options with this command. The name is actually the section and the key separated by a dot, and the value will be escaped
git config [<file-option>] [--type=<type>] [--show-origin] [-z|--null] name [value [value_regex]]
git config [<file-option>] [--type=<type>] --add name value
git config [<file-option>] [--type=<type>] --replace-all name value [value_regex]
git config [<file-option>] [--type=<type>] [--show-origin] [-z|--null] --get name [value_regex]
git config [<file-option>] [--type=<type>] [--show-origin] [-z|--null] --get-all name [value_regex]
git config [<file-option>] [--type=<type>] [--show-origin] [-z|--null] [--name-only] --get-regexp name_regex [value_regex]
git config [<file-option>] [--type=<type>] [-z|--null] --get-urlmatch name URL
git config [<file-option>] --unset name [value_regex]
git config [<file-option>] --unset-all name [value_regex]
git config [<file-option>] --rename-section old_name new_name
git config [<file-option>] --remove-section name
git config [<file-option>] [--show-origin] [-z|--null] [--name-only] -l | --list
git config [<file-option>] --get-color name [default]
git config [<file-option>] --get-colorbool name [stdout-is-tty]
git config [<file-option>] -e | --edit
--local # write to the repository .git/config file
--global # write to global ~/.gitconfig
--system # write to system-wide $(prefix)/etc/gitconfig
-e, --edit # opens an editor to modify the specified config file
--replace-all # Default behavior is to replace at most one line. This replaces all lines matching the key
--add # adds a new line to the option without altering any existing values
--get key [value-regex] # print the value of the key where the key corresponds exactly and the value if necessary with the pattern
--get-all key [value-regex] # same as --get but return all values
--get-regexp key-regex [value-regex] # print all "key value" pairs whose key/value pair corresponds to its pattern
--get-urlmatch section[.var] URL # when given a two-part name section.key, the value for section.<url>.key whose <url> part matches the best to the given URL is returned (if no such key exists, the value for section.key is used as a fallback)
--worktree # similar to --local except that .git/config.worktree is read from or written to if extensions.worktreeConfig is present
-f config-file, --file config-file # use the given config file instead of the one specified by GIT_CONFIG
--blob blob # similar to --file but use the given blob instead of a file
--remove-section # remove the given section from the configuration file
--rename-section # rename the given section to a new name
--unset # remove the line matching the key from config file
--unset-all # remove all lines matching the key from config file
-l, --list # list all variables set in config file, along with their values
--type <type> # ensure that any input or output is valid under the given type constraint(s)
bool / int / bool-or-int / path / expiry-date / color
-z, --null # output values and/or keys, always end values with the null character (instead of a newline)
--name-only # output only the names of config variables for --list or --get-regexp
--show-origin # Augment the output of all queried config options with the origin type and the actual origin
USED
git config
--system core.editor vim # set the default editor
--system merge.tool meld # set the default editor/viewer for diff
--global user.name "aguy tech" # set the name of user
--global user.email "aguytech@free.fr" # set the email of user
-l # print all configurations
-l --system # print system configurations
-l user.email # print values of configuration for a name
--get-all core.editor # print all defined values (local, global, system) for the key 'core.editor'