Git Basic Commands

1. Introduction to Git

(1) Git is an open source (developed by Linus Torvalds to help manage Linux kernel development) distributed version control system for agile and efficient processing of any small or large project, with commonly used version control tools CVS, SVN, etc. Different, it adopts the way of distributed version library, without server-side software support.

(2) Git's workspace, staging area and repository:

  • Workspace: This is the directory you can see on your computer.
  • Temporary storage area: English is called stage, or index. It is generally stored in the index file (.git/index) under the ".git directory", so we sometimes call the temporary storage area an index.
  • Repository: The workspace has a hidden directory .git, which is not a workspace, but a Git repository.

2. Installation

Git currently supports Linux/Unix, Solaris, Mac and Windows platforms.

(1) Install Git on Windows

It is easy to install Git on the Windows platform. There is a project called msysGit that provides an installation package. You can download the exe installation file from the GitHub page and run it (installation package download address: https://gitforwindows.org/ )

After the installation is successful, you can use the command line git tool (already comes with an ssh client, right-click -> "Git Bash") to perform Git operations, and there is also a graphical interface Git project management tool

(2) Other installations See the rookie tutorial:  http://www.runoob.com/git/git-install-setup.html

3. Use

(1) Basic use

1. git init can create a new Git repository in the / directory at any time, fully localized:

git init //在目录中创建新的 Git 仓库,缺省情况下 Git 就会为你创建"master"分支

After the creation, the ".git" subdirectory will be generated in the project. This is your Git repository, where all your snapshot data for this project is stored, eg:

2. git clone Copy a Git repository to the local for viewing and modification:

 git clone [url] //默认,Git 会用此 URL 最后一个“/”之后的名称作为本地项目名称,你也可以在该命令后加上你想要的名称: git clone [url] <project name>

eg.:

First, go to coding (a more popular Git server) to find a random project and copy the Git repository address:

Then, right-click on your local computer and select "git clone":

3. git add adds the file to the cache

New projects can use the " git add .   " command to recursively add all files in the current working directory.

4. git status to see if there have been changes since your last commit

git status -s //查看状态, -s表示short,如果不加会详细输出内容
/** git status -s 状态码解析*****************
  A: 你本地新增的文件(服务器上没有).   
  C: 文件的一个新拷贝.   
  D: 你本地删除的文件(服务器上还在).  
  M: 文件的内容或者mode被修改了.    
  R: 文件名被修改了。   
  T: 文件的类型被修改了。   
  U: 文件没有被合并(你需要完成合并才能进行提交)。  
  X: 未知状态(很可能是遇到git的bug了,你可以向git提交bug report)  
  ?:未被git进行管理,可以使用git add file1把file1添加进git能被git所进行管理
  这些状态也会组合出现,eg:
 "AM" :意思是,这个文件在我们将它添加到缓存之后又有改动,改动后我们再执行 git add 命令将其添加到缓存中
 "UU" :
**/

5. git diff View detailed information about the results of executing git status

git diff compares the difference between the current file in the working directory and the staging area snapshot, that is, the changes that have not been staged after modification. git status shows you the changes since the last commit or changes that were written to the cache, while git diff shows what those changes were, line by line:

  • Changes not yet cached: git diff
  • View cached changes:  git diff --cached
  • See all cached and uncached changes: git diff HEAD
  • Show a summary instead of the whole diff: git diff --stat

6.git commit

 git add writes the content you want to snapshot into the cache, and git commit adds the cache content to the repository.

git commit 
git commit -m "<message>" //使用 -m 选项以在命令行中提供提交注释
git commit -a //把unstaged的文件变成staged(不包括新建(untracked)的文件)然后commit,一般还是推荐先git add再git commit
git commit -am "<message>"//或 git commit –a –m "<message>",相当于git add . + git commit –m "<message>"合并使用
git commit --amend //增补提交,会使用与当前提交节点相同的父节点进行一次新的提交,旧的提交将会被取消.

Git records your name and email address for every commit you make, so the first step is to configure your username and email address

7. git reset HEAD cancels the cached content of the previous git add, but does not include the cache in the next commit snapshot.

The HEAD keyword refers to the latest commit at the end of the current branch, that is, the latest version on the branch in the repository.

git reset HEAD //把add进去的文件从staged状态取出来,可以单独针对某一个文件操作: git reset HEAD <filename>
git reset --mixed HEAD//--mixed是缺省参数,是将git的HEAD变了(也就是提交记录变了),但文件目录并没有改变, 取消了commit和add的内容.
git reset --soft HEAD// 实际上,是git reset –mixed id 后,又做了一次git add.即取消了commit的内容.
git reset --hard HEAD//是将git的HEAD变了,文件也变了.
     按改动范围排序如下:
     soft (commit) < mixed (commit + add) < hard (commit + add + local working)

8. git revert HEAD: undo the most recent commit:

  git revert will create a new commit in reverse, and you can tell Git not to commit first with the parameter -n.

9. git rm removes a file from the tracked file list:

If you simply manually delete the file from the working directory, you will be prompted with Changes not staged for commit when running git status. To remove a file from Git, it must be removed from the tracked file list, and then committed:

git rm <file>
git rm -f <file> //如果删除之前修改过并且已经放到暂存区域的话,则必须要用强制删除选项 -f
git rm --cached <file>//仅从跟踪清单中删除,把文件从暂存区域移除但仍保留在当前工作目录中使用
git rm –r * //递归删除,即如果后面跟的是一个目录做为参数,则会递归删除整个目录中的所有子目录和文件

10. The git mv command is used to move or rename a file, directory, or soft link:

git mv <file> <new file>

11.git clean removes files without track from the working directory:

git clean -d// -d表示同时移除目录
git clean -f// -f表示force,因为在git的配置文件中, clean.requireForce=true,如果不加-f,clean将会拒绝执行.

12. git stash pushes the current changes onto a stack:

git stash will push all changes in the current directory and index (but not untracked files) onto a stack, and then leave you in a clean working state, which is at the last commit

git stash list//显示这个栈的list.
git stash apply//取出stash中的上一个项目(stash@{0}),并且应用于当前的工作目录.也可以指定别的项目,如:git stash apply stash@{1}
git stash pop//在应用stash中项目的同时想要删除它
git stash drop// 删除上一个,也可指定参数删除指定的一个项目
git stash clear// 删除所有项目

13.git reflog manages reflog

Reflog is a mechanism used by git to record reference changes, such as recording changes in branches or changes in HEAD references, git will record the changes in the reflog file corresponding to HEAD, the path of which is . reflog files are placed in subdirectories under the .git/logs/refs directory

git reflog//不指定引用的时候,默认列出HEAD的reflog。HEAD@{0}代表HEAD当前的值,HEAD@{3}代表HEAD在3次变化之前的值.

 (2) Git branch management

Almost all version control systems support branches. Using branches allows you to detach from the main line of development and continue work without affecting the main line.

1. Create a branch:

git branch (branchname) //没有参数时,git branch 会列出你在本地的分支。

2. Switch branches:

When you switch branches, Git replaces the contents of your working directory with a snapshot of the branch's last commit, so multiple branches don't require multiple directories.

git checkout (branchname) //该分支存在则切换到分之下否则创建新分支并立即切换到该分支下

3. Merge the branch:

Git merging is not just simple file additions and removals, but also merges changes. You can merge into the unified branch multiple times, or you can choose to delete the merged branch directly after the merge.

git merge (branchname)  //将此分支合并到主分支去
git checkout -b (branchname) //创建并切换到新的分支,相当于git branch newbranch + git checkout newbranch 合并使用
git checkout <filename>//此命令会使用HEAD中的最新内容替换掉你的工作目录中的文件,已添加到暂存区的改动以及新文件都不会受到影响。会删除该文件中所有没有暂存和提交的改动,这个操作是不可逆的

If there is a conflict in the merge, you need to manually modify it, then:

git add // 解决了冲突要告诉 Git 文件冲突已经解决
git merge --abort//或者你也可以取消merge

4. Delete the branch:

git branch -d (branchname)

5. View the last commit of the branch:

git branch -v

(3) Git log to view the commit log

The best thing about Git is its merge tracing capabilities. Use the git log command to view the commit history:

git log
git log --oneline //查看历史记录的简洁的版本
git log --reverse --oneline //逆向显示所有日志
git log --oneline --number //显示number条,每条log只显示一行
git log --oneline --graph //图形化显示分支合并历史
git log branchname// 显示特定分支的log
git log --oneline branch1 ^branch2//查看在分支1不在分支2中的log,^表示排除这个分支
git log --decorate//会显示出tag信息
git log --grep //根据commit信息过滤log: git log --grep=keywords 默认情况下, git log --grep --author是OR的关系,即满足一条即被返回,如果你想让它们是AND的关系,可以加上--all-match的option
git log -S: filter by introduced diff ,如: git log -SmethodName (注意S和后面的词之间没有等号分隔).
git log -p//每一个提交都是一个快照(snapshot),Git会把每次提交的diff计算出来,作为一个patch显示给你看,另一种方法是git show [SHA].
git log --stat//同样是用来看改动的相对信息的,--stat比-p的输出更简单一些.
//--no-merges可以将merge的commits排除在外.

With the --graph option, the topology graph option is turned on, and you can more clearly see when branches and merges occurred in the history, eg.:

$ git log --oneline --graph
*   88afe0e Merge branch 'change_site'
|\  
| * d7e7346 changed the site
* | 14b4dca 新增加一行
|/  
* 556f0a0 removed test2.txt
* 2e082b7 add test2.txt
* 048598f add test.txt
* 85fc7e7 test comment from runoob.com

If you only want to find the commit log of the specified user, you can use the command: git log --author , eg.:

$ git log --author=Linus --oneline -5 //找 Git 源码中 Linus 提交的部分
81b50f3 Move 'builtin-*' into a 'builtin/' subdirectory
3bb7256 make "index-pack" a built-in
377d027 make "git pack-redundant" a built-in
b532581 make "git unpack-file" a built-in
112dd51 make "mktag" a built-in

If you want to specify a date, you can implement several options: --since and --before, --until and --after, eg.:

$ git log --oneline --before={3.weeks.ago} --after={2010-04-18} --no-merges //看 Git 项目中三周前且在四月十八日之后的所有提交,我可以执行这个, --no-merges 选项以隐藏合并提交
5469e2d Git 1.7.1-rc2
d43427d Documentation/remote-helpers: Fix typos and improve language
272a36b Fixup: Second argument may be any arbitrary string
b6c8d2d Documentation/remote-helpers: Add invocation section
5ce4f4e Documentation/urls: Rewrite to accomodate transport::address
00b84e9 Documentation/remote-helpers: Rewrite description
03aa87e Documentation: Describe other situations where -z affects git diff
77bc694 rebase-interactive: silence warning when no commits rewritten
636db2c t3301: add tests to use --format="%N"

(4) Git tags

1. If you want to always remember that particular commit snapshot at an important stage, you can tag it with git tag, eg.:

git tag -a v1.0 //给最新一次提交打上(HEAD)"v1.0"的标签,-a 选项意为"创建一个带注解的标签",不用 -a 选项也可以执行的,但它不会记录这标签是啥时候打的,谁打的,也不会让你添加个标签的注解。推荐创建带注解的标签

2. View tags:

$ git tag//查看所有标签
v0.9
v1.0

3. If we forget to tag a commit and publish it again, we can append a tag to it, eg.:

$ git tag -a v0.9 85fc7e7 //给发布提交的 85fc7e7 追加标签
$ git log --oneline --decorate --graph
*   88afe0e (HEAD, tag: v1.0, master) Merge branch 'change_site'
|\  
| * d7e7346 (change_site) changed the site
* | 14b4dca 新增加一行
|/  
* 556f0a0 removed test2.txt
* 2e082b7 add test2.txt
* 048598f add test.txt
* 85fc7e7 (tag: v0.9) test comment from runoob.com

4. Specify label information:

git tag -a <tagname> -m "<message>"

5. PGP signature tag:

git tag -s <tagname> -m "<message>"

6. To delete tags:

git tag -d <tagname>

7. View the content modified by a version of a tag:

git show <tagname>

4. Git warehouse

Git doesn't have a central server like SVN. Git commands are executed locally if you want to share your code or collaborate with other developers via Git. You need to put the data on a server that other developers can connect to.

(1) Add remote library

To add a new remote repository, you can specify a simple name for future reference. The command format is as follows:

git remote add [shortname] [url]

There are many popular Git repositories, the most used are: GitHub, Coding (both SVN, Git). The specific use is as simple as ordinary software, and you can get started directly

(2) Using Git repository

1. View the current remote library

Because you don't need to use the full url every time, Git creates an alias for each remote repo url, and then uses git remote to manage the list. If you clone a project, Git will automatically add the original url. The alias is called: origin

git remote// 列出remote aliases.
git remote -v//查看每一个别名对应的实际url.
git remote add [alias] [url]// 添加一个新的remote repo.
git remote rm [alias]// 删除一个存在的remote alias.
git remote rename [old-alias] [new-alias]//重命名
git remote set-url [alias] [url]//更新url, 可以加上—push和-fetch参数,为同一个别名set不同的存取地址.

2. Extract the remote warehouse

git fetch //取所有你本地没有的数据,取下来的分支(remote branches)和本地分支一样(可以看diff、log、merge),但是Git不允许你checkout到它们
git fetch [alias]//取某一个远程repo
git fetch --all//取到全部repo

3. Push to remote warehouse

① Download new branches and data from the remote warehouse

 If multiple people push code to the same remote repo, Git will first run git log on the branch you are trying to push, and check if it can see the current tip of the branch on the server in its history, if not in the local history The tip of the server indicates that the local code is not up-to-date, and Git will reject your push and let you fetch, merge, and then push, which ensures that all changes will be taken into account

git push [alias] [branch] // 把当前分支merge到alias上的[branch]分支,如果分支已经存在,将会更新,如果不存在,将会添加这个分支.
git push (remote-name) (branch-name) //(local-branch)缺省就意味着删除remote-branch

② git merge extract data from the remote warehouse and try to merge into the current branch

git merge [alias]/[branch] 

Git rebase will not generate merged commits, it will temporarily save all local commits as patches (patch) in the ".git/rebase" directory, then update the current branch to the latest branch tip, and finally save the patch applied to the branch.

//rebase的过程中,也许会出现冲突,Git会停止rebase并让你解决冲突,在解决完冲突之后,用git add去更新这些内容,然后无需执行commit,只需要: 
git rebase --continue//就会继续打余下的补丁
git rebase --abort//终止rebase,当前分支将会回到rebase之前的状态

4. Delete the remote warehouse

git remote rm [别名]

5. git pull default parameter == fetch + merge FETCH_HEAD

git pull//== git pull --merge,先执行git fetch,然后执行git merge把取来的分支的head merge到当前分支产生一个新的commit   
git pull --rebase//先执行git fetch,然后执行git rebase

(3) Build your own Git repository

You can also build your own Git server, see: http://www.runoob.com/git/git-server.html

1. Install Git

$ yum install curl-devel expat-devel gettext-devel openssl-devel zlib-devel perl-devel
$ yum install git

Create a git user group and user to run the git service:

$ groupadd git
$ useradd git -g git

2. Create a certificate to log in

Collect the public keys of all users who need to log in. The public keys are located in the id_rsa.pub file, and import our public keys into the /home/git/.ssh/authorized_keys file, one per line. Create it without this file:

$ cd /home/git/
$ mkdir .ssh
$ chmod 755 .ssh
$ touch .ssh/authorized_keys
$ chmod 644 .ssh/authorized_keys

3. Initialize the Git repository

Select a directory as the Git repository:

$ cd / home
$ mkdir gitrepo
$ chown git:git gitrepo/
$ cd gitrepo

$ git init --bare runoob.git
Initialized empty Git repository in /home/gitrepo/runoob.git/

The above command Git creates an empty repository. Git repositories on the server usually end with .git. Then, change the user of the repository to git:

$ chown -R git:git runoob.git

4. Clone the repository

$ git clone [email protected]:/home/gitrepo/runoob.git
Cloning into 'runoob'...
warning: You appear to have cloned an empty repository.
Checking connectivity... done.

5. The current mainstream code compilers have integrated version control systems

Taking webstorm as an example, you can use it after installing git:

They are: pull, commit

branch (branch) management

Right click on the project name and you will see the git option

ps: You can see the compilation log in the local history of webstorm itself (the project is stored in the ".idea folder" generated by webstorm after running). Right-click on the project name to see the local history option

After opening, you can see the record of each modification, and you can also revert to restore the code, as follows:

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324133573&siteId=291194637