preface
This manual (hereinafter referred to as “it”) is not a Git introduction tutorial. If you want to get started with Git, it is recommended to check out Liao Xuefang’s Git tutorial
This is just a personal record of the command manual and some understanding of Git, if there is not correct place welcome to comment, but also hope to help more learning Git partners.
It contains almost all high-level Git commands and some low-level Git commands. Each command has detailed explanations and examples to tell you how to use it and what to pay attention to when using it. Content according to the module partition, such as the add related commands can be concentrated in a module, you can choose your module free of interest in reading, because some of the command options very much but are not commonly used, so the manual may not record, if you want to see a command, all the options, please refer to the Git command reference.
“For simple commands that may not be recorded here, the () is used as a full name. For example, {u(upstream)}, which means” u “is the full name of” u “, you can use @{u} or @{upstream}.
Git itself is a content-addressing file system. At its core, Git is a simple key-value database. You can insert any type of content into a Git repository, and it returns a unique key that can be used to retrieve that content at any time.
Tips:
Some Git options with the same name can also be used in similar places. For example, the –abort option can be paired with git merge –abort to undo a merge operation, or git rebase –abort to undo a rebase operation.
Most of the Git options can be used together, Git log –author=’internetwei’ –after=”2020-01-01″ –before=”2020-06-01″ –no-merges — WXReader/Book/BookRack/BookReader
This command combines up to five options (specify author, specify start time, specify end time, do not merge commit, specify path). It means: Print internetwei author in January 1, 2020 to 2020 between June 1 to WXReader/Book/BookRack/BookReader this folder (including all documents folder) modified all submitted records but not including merger submitted.
- You don’t need to copy the entire hash string in Git where you need to use the hash value. Usually, you only need to copy the first 6 to 8 characters, and if the project is large, you can expand to the first 8 to 10 characters, even if it is like
Linux
Such items need only the first 10-12 characters to be unique.
The characteristics of the Git
-
How does Git treat files differently than SVN(other version control tools)?
Git does not save file differences or changes. Instead, it saves a snapshot of the file (a snapshot can be simply a copy of the file). If a file has not changed since it was committed, Git only keeps a link to the previously stored content. The SVN saves the difference when the file is committed.
-
How does Git ensure integrity?
Git calculates a checksum for all data before storing it. The mechanism for calculating the checksum is called sha-1 hash, which is a string of 40 hexadecimal characters (0, 9,a, f) based on the contents of the file and the directory structure. So when you store a file in the Git repository, if Git finds it already exists, it will simply create a link to the previously stored object), and the calculated hash will look like this: A6b6695a3594cc79b3c3fa9ef5772df036ec8d8e, calibration and the first two characters for named subdirectory, the remaining 38 character is used as the filename, Git information saved in the database are based on the hash values to index.
-
What does Git staging and committing do?
When you perform a staging operation, Git calculates a checksum for each file, and then adds the checksum to the staging area for commit.
When you commit, Git calculates checksums for each subdirectory and creates snapshots and indexes for all files. Git then saves the checksums as a tree object in the repository, and Git creates a commit object. It contains a pointer to the uppermost tree object and a pointer to the parent object (two in the case of a merge invocation, as shown in Figure 1), the author’s name, email address, and submission instructions.
Figure 1
-
What the Git staging area does
Most versions of SVN do not have the concept of a temporary area, and Git’s add command is different from the add command of other similar tools, which add files to the version management, but Git’s add command has three functions: 1. Add untracked files to version management; 2. Add the modified file contents to the temporary storage area. 3. Mark the conflict file as resolved. Because of the Git staging area, you can review your commit before you complete it and have precise control over each line of commit. For example, a file has 20 lines for fixing bugs and another 100 lines for adding new features. Now I only want to commit the 20 lines for fixing bugs in this file, so I just need to add those 20 lines to the temporary store.
-
The Merge of logic
If Git finds it possible to fast-forward a merge, Git will redirect the current branch directly to the latest commit of the merged branch. (One drawback of fast-forward merging is that when you delete the merged branch, you won’t know from which branch it was merged. To disable fast-forward merging, use the –no-ff option. Git creates a merge commit. If it is not possible to fast-forward the merge, Git does a simple three-way merge using the end commit object of both branches and the first common ancestor commit of both branches.
-
GPG signatures
GPG signatures you can submit or label, it can effectively improve the security of the Git repository, because it can prove this submission or label is submitted by computer you trust rather than a hacker using your name that is given a submission object is more modification, even if the hacker through some way to get right to the Git repository, speaking, reading and writing, He also has no way to add or use –force to modify any submissions or tags with your GPG signature.
Because Git’s author name and email address are optional, if someone changes their author name and email address to be the same as yours and somehow pushes the code to your repository… This can lead to losses for you or someone else, and using a GPG signature can help prevent this from happening. A GPG signed submission is shown on Github in Figure 2. You can click on the tag to see the specific signature information.
Figure 2
-
What’s HEAD?
The HEAD is essentially a pointer, also known as a symbolic pointer, because it usually points to a branch (symbol) that you can use to get the current state of your repository. You can use git symbolic-ref HEAD to see the current state of the HEAD.
When the HEAD to a specific object, not referenced branch, Git you will be prompted in the “free state”, “free state”, said you are not currently in any branch, so you can’t commit, view have to be submitted to the content of the snapshot, can also be modified in the running, if you want to commit to the need to create a branch, Free state is usually used to debug or roll back a commit.
-
The difference between HEAD^ and HEAD~?
When not followed by a number, ^ and ~ have the same meaning, indicating the first parent commit object; If followed by Numbers have difference, ^ behind only with the number 1 or number 2, submit 1 of father ^ 1 according to the current object, ^ 2 said the current object’s parent submit 2, only merge submission object have a father to submit 2, 1 parent submitted is accept merge branches at the time of merger, the second parent has submitted a is merged by combined the branch; ~1 is the first parent of the current commit, ~2 is the second parent of the current commit, and so on. ~2 is the same as ~~, but when you want to represent the 100th parent of the current commit, it’s more realistic to use ~100 than to write 100 ~. You can use a combination of ~ and ^. For example, git show HEAD~2^2 shows the second parent commit of the current commit.
-
Dangerous Git commands
In Git, almost any committed content can be recovered (and overwritten commits can also be recovered), but uncommitted content can never be recovered. Any command that causes a workspace to be lost is a dangerous command. There are three types of dangerous commands in Git:
- All take
-f
Option,-f
Is the full name of--force
It means to force, for examplegit push -f
Means to forcibly push a local repository to a remote repository,git switch -f dev
To forcibly switch to the dev branch-f
Choose carefully. git reset
The command has a total of three options,--soft
,--mixed
,--hard
Of which only--hard
Options are dangerous commands, the other two are safe when you use them--hard
Git overwrites the workspace with the snapshot content specified in the repository.git checkout
Git overwrites the specified file in the workspace with the snapshot content specified in the repository. (Switch is recommended.) To prevent misoperation resulting in the loss of file content).
- All take
-
The difference between checkout and Reset
Many people get confused with checkout and Reset because they both have the same end result, but the implementation process is different. Simply put, the checkout command changes the HEAD pointer directly, while the reset command changes the object to which the HEAD pointer points.
Let’s say the master branch has a commit object (ab4adf) and you want to roll back to that commit. Git offers two ways to do this: Git checkout ab4adf and Git reset –hard AB4adf. Git checkout ab4adf will direct the HEAD pointer to the commit object and then overwrite the workspace with a snapshot of the commit object (if you look closely, git will tell you that you are currently in the HEAD free state), as shown in Figure 3. Git Reset — A slightly more complex implementation of hard AB4ADf manipulates the object to which the HEAD pointer points (in this case, the master branch) to the AB4ADf commit, and then overwrites the staging and workspace contents with the snapshot content from the AB4ADf commit, as shown in Figure 4.
Figure 3Figure 4.
-
Git protocol differences
The HTTP protocol
HTTP protocol has two versions, one is dummy protocol (can only read warehouse content through GET), the other is intelligent protocol, dummy protocol has basically quit the stage due to its own problems; Compared with SSH protocol, HTTP protocol can use the user name and password for authorization, even without knowing the user name and password can also obtain the project, which is suitable for the promotion of open source projects, another advantage is that HTTPS protocol is widely used, the general enterprise firewall will allow the data through these ports. The only downside is that on some servers, setting up the HTTPS server is a little trickier
Git config –global credential. Helper cache to temporarily cache the username and password in memory when you need to re-enter the username and password using HTTPS. You can use the –timeout
option to control the retention period. The default is 900 seconds (15 minutes).
SSH protocol
The SSH protocol is relatively simple to set up. The SSH daemon process is common, and most administrators will use it. Most operating systems include it and related management tools. The downside is that it does not support anonymous access to Git repositories, and even to read data, users must access your host via SSH, so SSH is not good for open source projects
The Git protocol
The fastest transmission speed of any protocol, because there is no overhead of encryption and authorization; It is also the most difficult protocol to set up. It also requires firewalls to open port 9418, but enterprise firewalls generally do not open this non-standard port. Git is usually used in conjunction with other protocols (such as HTTPS). Git is used for pull and HTTPS is used for push.
The Local agreement
Generally not used, all did not go to understand the knowledge of this aspect, interested can search
Git Common Commands
-
Git help
Gets the help for a specified git command
Example:
Git help add Obtain the help document of the add command
-a Lists all Git commands
-c(–config) lists all available configuration variables
Git Add -h simple version of the help document
Equivalent commands:
git <verb> –help
man git-<verb>
-
Git rm
Deletes the specified file –cached(–staged) Removes the specified file from the staging area
If you accidentally add a file to your Git repository that you want to ignore, you will be notified that the file is not saved every time you commit, even if you declare it in the Ignored file. You can use this command to delete the specified file from the staging area without affecting the workspace.
-n(–try-run) Lists the files to be deleted
-
Git Describe
generates a string build number based on the specified commit object. It consists of the last tag name of the commit object, the number of commits since that tag, and the partial hash of the commit you described (you can attach a readable name to the commit).
-
Git reflog displays all referenced logs
The essence of reflog is to keep a record of changes to the HEAD pointer. It only exists in the local repository, and generally Git only keeps records for the last few months (90 days by default)
-
Git reflog – date = local – all | grep branch of < name > for specified branch HEAD change record
Can be used to see on which branch a branch was created, because reflog only works on the computer on which the branch was created and can fail over time.
-
Git clean removes files that are not tracked by Git. This command should be executed with the following options
-d deletes files/folders in subdirectories recursively
-f If clean.requireForce is not set to false, you must use -f to tell Git which files need to be deleted
-n(–dry-run) displays only the files that will be removed
-x does not delete ignored files by default. -x indicates that ignored files will be removed
-x Deletes only the untracked files that are ignored
-
The Git GC manually packages and optimizes the Git repository
Aggressive With this option Git will spend more time optimizing the repository
-
Git FSCK verifies the validity of objects in the database
–unreachable Prints objects that exist but cannot be accessed from any node
-
Git Restore Restores files in the workspace
–staged
Removes the specified file from the staging area -s(–source)
Restores the specified files in the workspace using the files in the specified tree -
Git clone -d < branch name >
–depth= Example:
Git clone -b master
–depth=1 Last commit of the master branch of the clone repository
Git Config
-
Git config –list Check git configuration information. The configuration information may be repeated.
–show-origin displays the source (path) of the configuration.
-
Git config < range > < options > < value > sets the specified configuration information in the specified range.
Example:
Git config –global user.name ‘author’ sets the name of the committer globally. Git Config has three ranges: system, global, and local(default). The weight increases in the order of weight. System has the largest impact range, which applies to all Git repositories under the current computer. Global is valid for all Git repositories under the current user. Local is only valid for the current Git repository.
-
Git config –global merge.conflictstyle diff3 change the merge conflictstyle to diff3, which displays additional base content, as shown in figure 5.
Figure 5
-
Git config –global help.autocorrect 50 If this option is set, git will automatically execute this command after the countdown ends if a similar command is matched
-
Git config –global core. cascade true With this function enabled git automatically converts a carriage return and newline to a newline when you submit, and a newline to a carriage return and newline when you check out the code.
In some Windows editors, a newline is a combination of a carriage return and a newline, while in macOS and Linux, a newline is a single character. If the same project is being developed on Windows and another platform, you may encounter space conflicts.
Setting input to INPUT tells Git to convert carriage returns and newlines to newlines on commit, but not on checkout
-
Whitespace. Git provides six main options for handling extra whitespace characters. Three are enabled by default, and three are disabled by default
Default enabled: blank-at-eOL (look for Spaces at the end of a line), blank-at-eof(stare at blank lines at the bottom of a file), space-before-tab(watch for Spaces before tabs in your outfit)
Default: indent-with-non-tab(find lines that start with a space instead of a TAB, you can control this with the tabwidth option), tab-in-indent(monitor for tabs that indent at the beginning of a line), cr-at-eol(tell Git to ignore carriage returns at the end of a line)
If you want to turn off an option, you can either leave it unspecified or precede it with a –
-
Git config < scope > alias.< alias >’ < full name >’ sets a Git alias in the specified scope.
Example:
Git config –global alias.st ‘status’ sets a global alias for status.
Aliases are often used to simplify commands. If you want to alias a non-Git command, such as gitk, you can set Git config –global alias.gitk ‘! Gitk ‘, the “gitk” command is executed when you call “git gitk”.
Some common aliases:
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.s 'status -s'
git config --global alias.last 'log -1'
-
Git config < scope > –unset alias.
Deletes the specified alias
Git Diff
-
Git Diff shows the difference between a workspace and a staging area
–cached(– Staged) shows the difference between the staging area and the latest commit
–check Prints all possible space errors
–ours collide. what does merge introduce
— What’s the difference between the result of the merge when checking the possession-b conflict and the other side where -b means removing space
— How do files change on both sides when base conflicts
Git Log
-
Git log displays the commit history for the current branch
-n Displays a specified number of commit records. For example, git log-2 displays the last two commit records
–show-signature Displays GPG signature information
–stat displays brief information at submission time
–abbrev-commit displays short hashes
–relative-date displays a relative time (e.g. 9 hours ago)
Graph displays the branch and merge history as an ASCII graph next to the log
–oneline –pretty= short for oneline and –abbrev-commit
–pretty= Display the commit history in another format
Oneline displays each commit on a single line
Short does not show the submission time
Full does not display the submission time but displays the submitter information in addition
Fuller displays the submitter information and the submission time
Format Custom display style (custom style can not be affected by Git version)
Example:
Git log –pretty=format:”%Cred%h%Creset – %C(yellow)%an%Creset, %C(green)%ar%Creset: %s” git log –pretty=format:”%Cred%h%Creset – %C(yellow)%an%Creset, %C(green)%ar%Creset: %s” Submit instructions.
Format The options are as follows:
%H The complete hash value submitted
%h The shorthand hash value for submission
The full hash of the %T tree
Short for %t tree hash
%P The complete hash submitted by the parent
%p parent submitted hash for short
%an The name of the author
%ae author’s email address
% AD Author’s revision date
%ar The author’s revision date, shown in terms of how long ago, e.g. 20 hours ago
%cn Name of the submitter
% CE The email address of the submitter
% CD Submission date
% CR Submission date, shown in terms of how long ago
%s Submit instructions
Color options supported by Git:
Normal, black, red, green, yellow, blue, Magenta, Cyan, white
Font properties supported by Git
Bold, dim, ul, blink, reverse
— Author Displays and specifies the author’s commit record
Committer Displays and specifies committer’s committer records
–grep Displays the commit record that contains the specified string in the commit description
-s displays the commit record for changes to the specified string (often used to find the commit record for changes to a function)
-g < regular expression > Uses re to find the associated commit record
—
Displays the changes in the specified path (often used in conjunction with other options to find the changes committed by a function in a file) -l Displays the modification submission records of the specified function in the specified file
Example:
Git log – L: firstApplication: WXReader/AppDelegate. M show AppDelegate. M files related to the firstApplication commits
–no-merges Does not display merge commits
–after(–since) Displays commit records after the specified time
–before(–until) Displays submissions before the specified time
–after and –before can be used with specified time values, such as “2008-08-08”, or with relative dates such as “2 years 1 day 3 minutes ago”, “2. Weeaks”
Example:
git log –author=’internetwei’ –after=”2020-01-01″ –before=”2020-06-01″ –no-merges — WXReader/Book/BookRack/BookReader According to the author internetwei in January 1, 2020 to 2020 between June 1 to WXReader/Book/BookRack/BookReader this folder (including all the files in the folder) for all the modification submitted to but not including merger submitted
The branch of < 1 >.. < branch 2> Display branch 2’s committed record but branch 1’s not (used to check which branch commits are not pushed)
And.. Syntax equivalent commands:
Git log ^< branch 1> < branch 2>
Git < branch 2> --not < branch 1>
The above two commands are.. For example, git log refA refB ^refC shows all commit records that are included in refA or refB but not included in refC
Branch of < 1 >… < Branch 2> shows commits that are not shared by branch 1 and branch 2
– left, right and… You can use <, > to indicate left and right branches
-
Git shortlog Displays the current branch change log
Example:
Git shortLog –no-merges master –not v1.0
Git Rebase
Merge and Rebase Used to integrate different branches in the Git revision has two ways, one is the merge, the other is a rebase, the final result for the two no difference, just submitted is not the same as the history, rebase is a series of application submitted in accordance with the original sequence in turn to another branch, such doing can make a submission history more clean and tidy; And merging is putting the end result together. Extracting patches and changes introduced in a commit and then applying them once on top of the current branch is called rebase. The commit history after rebase is shown in Figure 6, and the commit history after merge is shown in Figure 7. For the same commit, the difference between merge and rebase is clear. You can choose either 'rebase' or 'merge', but if you choose 'rebase', remember to only 'rebase' submissions that have not yet been pushed or shared with others.Copy the code
Figure 6.
Figure 7.
-
Git rebase < branch > bases commits on the current branch to the target branch in turn
-
Git rebase < branch 1> < branch 2
Example:
Git rebase Master Experiment bases the submitted content on the experiment branch to the master branch in turn, as shown in Figure 8
Figure 8.
If you switch to the master branch and merge the experiment branch, there will be no fork commit history, as shown in Figure 9
Figure 9.
The principle of Rebase:
-
First, find the most recent common ancestor C2 of these two branches
-
The current branch is then compared to the previous commits of the ancestor, and the corresponding changes are extracted and stored as temporary files
-
Then point the current branch to the target base C3
-
Then apply the changes to the temporary files that you saved earlier
-
-
Git rebase –onto < branch 1> < branch 2> < branch 3
Example:
Git rebase –onto the master Server client finds the client branch, finds the commits it made after splitting from the server branch, and then replays those commits on the master branch, as shown in Figure 10
Figure 10.
-
Git rebase -i < interval > interactively rebases commits within a specified interval
Example:
Git Rebase-I HEAD~2 can be used to interactively base the last three commits. The interactive base function is very powerful, such as “compress any commit into one commit”, “split a commit into multiple commits”, “modify the commit description of any commit”, “reorder”, “remove the commit” and other functions
-
Git commit –amend Modifies the latest commit information
It starts with commit, but it’s essentially a rebase operation, so put it in rebase
This command has two functions:
-
Amend the latest submission notes; Make sure the current staging area is clean, then run this command, it will take you to the submit notes edit box, re-edit the submit information and save and exit.
-
Supplementary submission documents; For example, you forgot to add a file in the last commit, or you have changed the file in the last commit, which should be the same as the last commit. First, add the files to the staging area to make sure that the files in the staging area are the ones that you want to add to the staging area, then run this command to edit the commit information, save and exit.
-
-
Git cherry-pick
repeats the committed changes on the current branch and commits them
Git Remote
-
Git Remote displays the names of all remote repositories
-v Displays the specific information about the remote repository
Show < Repository name > Displays details about a specified remote repository
Ls-remote < Repository name > Displays a complete list of references to the specified remote repository
Prune < repository name > Delete branch information that exists in the local image repository but has been deleted remotely
Git remote set-url < repository name >
Modifs the address of the specified repository
-
Git fetch < repository name > pulls the specified repository information and updates the local repository information (this will only update the local remote mirror repository, not the local branch and workspace content)
-
Git pull is an abbreviation of fetch and merge. it pulls and merges new commits from upstream branches
The pull command requires that the branch have an upstream branch. If there is no upstream branch, an error message is displayed. It will run Git fetch to pull the information from the remote repository, and then run Git merge to merge the remote commit
-
Git branch -u(– set-ups-to) < remote branch reference > sets/modifs the upstream branch reference for the current branch
Git branch -u origin/dev sets the upstream branch of the current branch to the dev branch of the Origin repository
When a branch has an upstream branch, use {u(upstream)} instead of the upstream branch
-
Git push pushes new commits from the current branch to the upstream branch
Git push origin refs/head/dev: refs/head/dev is this push command, the full name of local dev branch pushed to the remote dev branch
Git push Origin v1.0
Git Push Origin — Tags pushes all tags to a remote repository
Git push Origin –delete dev Delete branch of remote repository
Git push Origin –delete v1.0 branch
Git push origin –delete is actually git push origin :refs/head/dev and pushes an empty object over the dev branch of the remote repository. Git usually saves data for a period of time until the garbage collection mechanism runs.
Git Tag
Difference between Tag and Branch: Similarity: Both are Pointers to a COMMIT object Difference: The Tag position is fixed, always pointing to a specific commit object. Branch changes location as the Branch is committed or rolled back. The difference between a lightweight Tag and a note Tag: A lightweight Tag is like a branch that does not change. It is just a reference to a particular commit. A Tag, on the other hand, is a complete Git object that contains information about who tagged it, when it was tagged, a description of the Tag, and support for GPG signing and validation.Copy the code
-
Git tag < tag name > Creates a lightweight tag for the current commit
-a Creates a note Tag
follows a hash value to create a Tag for the specified commit
-s Uses GPG to sign the label
-l(–list) “v1.*” Displays all tags that start with “v1.” and supports regular matches
-v Verifies the signature using GPG (provided the signer’s public key is in your keychain)
Git Branch
-
Git Branch displays all local branches
-v Displays the latest commit corresponding to the branch
-vv Displays the trailing/leading status of the branch and upstream branch
-merged Displays branches merged with the current branch
–no-merged Displays branches that are not merged with the current branch
Git Merge
-
Git merge < branch name > Merges the specified branch
–squash compresses multiple commits from a merge into a single commit
— Verify-signature refuses to merge submissions whose GPG signature verification fails
-xignore-space-change treats one whitespace character as equivalent to multiple consecutive whitespace characters
– xignore-all-space Ignores the blank changes completely when merging
-xours retains the changes of the current branch when it encounters a conflict
-xpossessive keep the target branch changes when a conflict occurs
-
Git merge-base < branch 1> < branch 2> Get the most recent public commit for two branches
-
Git merge –verity-signature -s < branch name > Generates a merge commit for a signature
-
Git merge -s ours < branch name > makes a fake merge and records a new merge commit with both branches as the parent, but it doesn’t even care which branch you are merging into, it simply records the current branch code as the result of the merge
If you have a forked release branch and do some work on it that you want to merge back to the master at some point in the future, and at the same time some bugfix on the master branch needs to be backported back to the release branch, You can merge the bugfix branch into the release branch and also merge -s ours into your master branch (even if that fix is already there) so that when you merge the release branch again later, there will be no conflicts from the bugfix.
Working with Git Email
-
Git format-patch -m < branch name > < branch name > < branch name >
Example:
Git format-patch-m Origin /master generates commit patches that are not shared between the current branch and the Origin/Master branch to the root directory (this generates a mail-able mbox file that converts each commit into an email). -m allows Git to check whether there is a commit to rename a file
-
Git apply –check
Checks whether patches in the specified path can be applied -
Git apply
Applies the patch content in the specified path -
Git am
is similar to Git Apply, but smarter — Resolved continues to apply the next patch
-3 indicates that Git attempts a three-way merge when a patch conflict occurs. This option is disabled by default
Am means: Apply a series of patches from the Mailbox
Git apply is used to apply patches created by git diff or Unix diff commands. It is almost equivalent to patch-p1, but git apply is more restrictive and accepts fewer fuzzy matches than patch. Git apply uses a “apply all, If the patch is created using Git format-patch, then it is recommended to use Git AM to apply the patch. Only for the old version of the patch, you must use Git Apply
Git Rerere
Rerere, which means "reuse recorded conflict resolution," is a way to simplify conflict resolution. When Rerere is started, Git maintains images before and after a successful merge, and when Git finds that a similar conflict has been fixed before, it uses the previous fix without your interventionCopy the code
-
Git config –global rerere. Enabled True Enables the rerere function
If you want to enable Rerere for an existing repository, manually create an RR-cache folder in the. Git folder
When Rerere is enabled, the volume of the local repository is increased. The RR-cache folder only exists in the local repository and is not pushed to the remote repository
-
Git checkout –conflict=merge
Restores the specified file to the state before Rerere execution
Git archive
-
Git archive < commit > — prefix = ‘< filename > after decompression/’ | gzip > < package name > tar. Gz submitted based on the specified object to create a zip file of all current snapshot content
Example:
Git archive master –prefix=’project/’ > gzip > master.tar.gz Create a tar
Git archive master –prefix=’project/’ –format=zip > ‘Git describe master’
-
Git Bundles package branches
Example:
Git Bundle Create Repo. Bundle HEAD Master packages all commit histories for the master branch
-
Git bundle verify
Checks whether the specified bundle is valid -
Git bundle list-heads
Lists references to specified bundles
Git Stash
-
Git Stash stores all uncommitted files that have been tracked and restores the staging and workspace changes
-u(– included-untracked) stores all tracked and untracked files (excluding ignored files)
-a(–all) Stores all files (including ignored files)
–keep-index Saves to storage without emptying the staging area
List View the list of all cached files
Apply restores the latest cache but does not delete it. You can specify a cache file
Pop is the same as apply but automatically deletes cached files (only if the restore is successful)
–index If added to pop and apply, the content in the staging area will be added back to the staging area. By default, everything will be restored to the workspace
-
Git stash < cache file > < Branch name > Creates a branch using the specified cache file
Git Add
-
Git Add adds files to the staging area
-i(–interactive) Uses the interactive terminal mode for the temporary storage
-p(–patch) Custom temporary patch file (this command is only a subcommand of -i)
Git Commit
-
Git commit Commits files from the staging area to the Git repository
-s Signs the submission using GPG
-m “Comment” Uses the specified comment as the submission
-a Adds all traced files to the staging area (untraced files will not be added to the staging area)
-am -a and -m are abbreviations of the commands
Git search
-
Git grep < string > searches for all locations in the workspace where the specified string appears
Example:
Git grep –break –heading -n -e ‘#define’ –and \(-e kEncryptionSecret -e kEncryptionKey \) v4.6.0 Check where the name of the constant contains either “kEncryptionSecret” or “kEncryptionKey” strings in the Git code base of the V4.6.0 tag
-n(–line-number) Indicates the number of lines displayed in the file
-c(–count) Displays the number of matches in the file
-p(–show-function) Displays the context content of the string
Git Subtree
Git submodules are not mentioned here, because they are more difficult to use than subtrees. For example, to switch branches in a repository with submodules, you need to reinitialize the modules. And it's simpler than git submodules.Copy the code
-
Git subtree add –prefix=
< branch name > Add contents of the specified branch in the specified repository to the specified path Example:
Git subtree add –prefix=sub/libpng master
-
Git subtree pull –prefix=
< branch name -
Git subtree push –prefix=
< branch name > Push subtree modification submission
Git Filter
-
Git Filter-branch overwrites the commit history
Example:
Git filter-branch –tree-filter ‘rm -f password.txt’ HEAD –tree-filter indicates that after checking out each submission of an item, run the specified command and then resubmit the result. To make the above command run on all branches, add –all
Git filter-branch –subdirectory-filter trunk HEAD Set the trunk subdirectory as the root directory of the project. Git automatically removes all commits that do not affect the subdirectory
git filter-branch --commit-filter ' if [ "$GIT_AUTHOR_EMAIL" = "[email protected]" ]; then GIT_AUTHOR_NAME="Scott Chacon"; GIT_AUTHOR_EMAIL="[email protected]"; git commit-tree "$@"; else git commit-tree "$@"; The fi 'head iterates over all the commits and changes the author name and email address if the author's email address is [email protected] (the hash of a commit is changed even if it is not).Copy the code
-
Git Filter-repo rewrites the commit history
It is recommended to use Git filter-repo instead of Git Filter-branch, because Git Filter-branch is riddled with pitfalls and low performance when rewriting commit history, and is designed to leak at every level of the interface. This makes it almost impossible to change anything about the design without backward compatibility. In comparison, Git Filter-repo has more features and performance is much higher (some sources say that a task done in a few hours with Git Filter-repo can take up to 3 months with Git Filter-branch).
Git filter-repo –path-rename
traverses the commit history and changes the author name from old_name to new_name
–tag-rename
iterates through the commit history and renames tags beginning with old and beginning with new, for example –tag-rename foo:bar will change foo-1.2 to bar-1.2
To learn about git filter-repo, check out the Git Filter-repo command manual
Git Show
-
Git show < branch name >@{yesterday
Yesterday can be any other time Git recognizes it
-
Git show
:To view the contents of the specified file under the specified commit
Git Reset
-
Git reset –soft < COMMIT > Moves the current branch to the specified commit (this will cause the Git repository and staging area to be inconsistent with the contents of the workspace, and the staging area will be consistent with the contents of the workspace, so Git will prompt you to commit to be consistent with the Git repository), as shown in Figure 11.
Figure 11.
-
Git reset –mixed
default behavior to move the current branch to the specified commit and update the contents of the staging area. At this point, Git will commit you to perform the add operation to add the files to be submitted to the staging area), as shown in Figure 12
Figure 12
-
Git reset –hard
Moves the current branch to the specified commit and updates the staging area and workspace. This is the only dangerous command for reset (doing so causes Git to update (overwrite) the staging area and workspace with the contents of the repository), as shown in Figure 13
Figure 13
-
Git reset
Deletes the specified file from the staging area It essentially calls the Git reset — Mixed HEAD
command to overwrite files in the staging area with the specified files in the repository, so it can remove files from the staging area
Git Checkout
-
Git checkout -b < branch name > create and switch to the specified branch
This command is actually an abbreviation of git branch and git checkout
It is recommended to use git switch < branch name > to switch branches, both because switch is easier to understand than checkout, and because the switch command is more secure than checkout. You may accidentally overwrite your workspace when using git checkout < file/branch name >.
-
Git checkout —
Undo changes to the specified files in the workspace This command overwrites the specified files in the workspace with the specified files in the current repository. Any changes to the files in the workspace will be lost
Git Revert
-
Git Revert
Restores the committed content
This command is used to reset the content of a commit and generate a new commit
Git Blame
-
Git blame -l
Check for a specified range of modification commit records in a specified file Example:
Git blame – 68100 WXYZ_BookReaderViewController. L m view WXYZ_BookReaderViewController m file submit records for 68-100 line modification
-c This option means that Git will analyze the file you are annotating and try to find the original source of the code fragments in the file
Git Bisect
-
Git Bisect uses binary search to find commits that introduce errors
Usage process:
Git bisect start starts binary search
Git Bisect bad tells Git that there is a problem with the current commit
Git bisect good
tells Git which commit is not a problem
Git Bisect Good tells Git that the current commit is ok
Git bisect reset Ends binary search
Git biesect start
quickly performs a binary lookup where the first parameter is an abnormal commit and the second parameter is a normal commit
Git bisect run
Executes the script for binary search
Git Replace
-
Git replace Replaces the specified object
Git replace
Replaces commit1 with commit2
Git Low-level commands
-
Git ls-files displays information about the index and files in the working tree
-u(–unmerged) Displays the hash value of the collision object
-s(–stage) Displays the current state of the staging area
-
Git rev-list lists the committed objects in reverse chronological order
–count < branch name > Views the number of commits for the specified branch
-
Git cat-file Displays information about the content or type and size of a specified object
-p Gets the content or type information of the specified object
-t Obtains the type of the specified object
-s Obtains the size of the specified object
-
Git ls-tree Lists the contents of a tree object
-r Specifies the contents of a recursive subtree object
-
Git update-ref updates the name of the object stored in the ref
Example:
Git update-ref refs/tags/v1.0 c7cfb9 Adds a lightweight tag to the specified commit
-
Git count-objects -v shows the detailed space occupied by the repository
-
Git for-eache-ref displays all references