
对于刚学 Git 的朋友来说太痛苦了,一堆命令,于是就有了这篇文章,对于常用的命令进行梳理。
- Workspace:工作区
- Index / Stage:暂存区
- Repository:仓库区(或本地仓库)
- Remote:远程仓库
1. 初始化
- 在当前目录新建一个Git代码库 - git init
- 初始化一个新目录 - git init [project-name]
- 下载远程仓库的项目到本地 - git clone [url]
2. 配置
配置文件分为全部配置和仓库配置,全局配置文件是 ~/.gitconfig,当前项目配置文件是 .git/config。
我们平时主要修改的就是 remote 和 user, remote配置的是远程仓库地址,user 配置的是你提交,推送时候用的用户名和密码,也会在 log 里面看到。
[user]
        name = 七月编程
        email = 七月编程@126.com
[remote "origin"]
        url = https://github.com/july/july.git
针对仓库的配置可以使用如下命令进行配置,如果是全局,添加 --global 即可。
git config user.name 七月编程
3. 添加/删除
- 添加指定文件到暂存区 - git add [file1] [file2] ...
- 添加指定目录到暂存区,包括子目录 
 `git add [dir]``
- 添加当前目录的所有文件到暂存区 - git add .
- 逐行检查并提交,y是确定,n是取消 - git add -p
- 删除工作区文件,并且将这次删除放入暂存区 - git rm [file1] [file2] ...
4. 代码提交
- 提交暂存区到仓库区,并填写备注 - git commit -m [message]
- 提交暂存区的指定文件到仓库区 - git commit [file1] [file2] ... -m [message]
- 修改上次的提交内容,需要修改没有 push 之前的提交 - git commit --amend
- 追加新的内容到上次没有 push 的提交 - git commit --amend --no-edit
5. 分支
- 列出所有本地分支 - git branch
- 列出所有远程分支 - git branch -r
- 列出所有本地分支和远程分支 - git branch -a
- 新建一个分支,但依然停留在当前分支 - git branch [branch-name]
- 新建一个分支,并切换到该分支 - git checkout -b [branch]
- 新建一个分支,与指定的远程分支建立追踪关系 - git branch --track [branch] [remote-branch]
- 切换到指定分支,并更新工作区 - git checkout [branch-name]
- 切换到上一个分支,这个操作很常见,也很有用 - git checkout -
- 建立追踪关系,在现有分支与指定的远程分支之间 - git branch --set-upstream [branch] [remote-branch]
- 合并指定分支到当前分支 - git merge [branch]
- 从其他分支合并 commit - git cherry-pick [commit]
- 删除本地分支 - git branch -d [branch-name]
- 删除远程分支 - git push origin --delete [branch-name]
6. 远程同步
- 下载远程仓库的所有变动 - git fetch [remote]
- 显示所有远端仓库的配置 - git remote -v
- 增加一个新的远程仓库,并命名 - git remote add [shortname] [url]
- 更新远程分支的变化 - git pull [remote] [branch]
- 推送本地指定分支到远程仓库 - git push [remote] [branch]
7.撤销
- 恢复暂存区的指定文件到工作区 - git checkout [file]
- 恢复暂存区的所有文件到工作区 - git checkout .
- 重置暂存区的指定文件,与上一次commit保持一致,但工作区不变 - git reset [file]
- 重置暂存区与工作区,与上一次commit保持一致 - git reset --hard
- 重置当前分支的指针为指定commit,同时重置暂存区,但工作区不变 - git reset [commit]
- 重置当前分支的HEAD为指定commit,同时重置暂存区和工作区,与指定commit一致 - git reset --hard [commit]
- 新建一个commit,用来撤销指定commit - git revert [commit]
- 暂时将未提交的变化暂存,然后再取出来 - git stash- git stash pop
8. 信息查询
- 显示有变更的文件 - git status
- 显示历史信息 - git log
- 搜索提交历史,根据关键词 - git log -S [keyword]
- 显示某个文件的版本历史 - git log --follow [file]
- 显示指定文件是什么人在什么时间修改过 - git blame [file]
- 显示暂存区和工作区的差异 - git diff
- 显示某次提交的元数据和内容变化 - git show [commit]
- 显示某次提交时,某个文件的内容 - git show [commit]:[filename]