导语
该文章主要参考于阮一峰的网络日志,记录一些常用的Git命令
配置Git
密钥
ssh-keygen -t rsa -C 'yours@email.com'#生成密钥
多账号SSH配置
1.生成指定名字的密钥
ssh-keygen -t rsa -C 'yours@email.com' -f ~/.ssh/git_test#生成git_test和git_test.pub文件
2.把密钥复制到托管平台(gitlab、github)
把git_test.pub内容复制到代码托管平台
3.修改config文件
vim ~/.ssh/config#修改config文件,如果没有创建config,添加如下:
Host test.github.com
HostName github.comame
User yourName
IdentityFile ~/.ssh/git_test
Host gitlab.test2.com
HostName gitlab.test2.com
User yourName
IdentityFile ~/.ssh/git_test2
修改个人信息
git config --global user.name "yourName"
git config --global user.email "yourEmail"
基本命令

- Workspace : 工作区
- Index/stage : 暂存区
- Repository : 工作区
- Remote : 工作区
新建仓库
git init [project-name] #新建目录
git clone [url] #下载项目(ssh或者https)
文件操作
添加
git add [file1] [files] ···#添加指定文件到暂存区
git add #添加所有文件到暂存区
删除
git rm [file1] [file2]···#删除文件,并把删除放入暂存区
提交
git commit -m [message] #提交暂存区到仓库区
git commit [file1] [file2]··· -m [message]#提交暂存区指定文件到仓库区
git commit -a #跳过暂存区,把追踪过的文件暂存起来一起提交
取消
git reset --hard #重置暂存和工作区,与上次commit一致
git reset --hard [commit] #重置到指定状态,与[commit]一致
git reset [file] #重置暂存区的指定文件,与上次commit一致
git revert [commit] #撤销指定commit
恢复
git checkout [file] #恢复暂存区的指定文件到工作区
git checkout [commit] [file] #恢复某个commit的指定文件到暂存区和工作区
git checkout#恢复暂存区的所有文件到工作区
查看
git status #显示变更文件
git log #显示当前分支版本
git log --stat #显示commit历史,及每次commit变更文件
git blame [file] #显示指定文件中的代码的修改时间和人
git diff #显示工作区和暂存区的区别
git diff --cached [file] #显示暂存区和上一次commit的区别
git diff --shortstat #显示今天写了多少行代码
git reflog #显示当前分支的最近几次提交
分支操作
查看
git branch #查看所有本地分支
git branch -a #查看所有本地和远程分支
新建
git branch [branchName] #新建分支,但是仍停留在当前分支
git checkout -b [branchName]#新建分支,并切换到该分支
切换
git checkout [branchName] #切换分支
git checkout - #切换到上次分支
删除
git branch -d [branchName] #删除本地分支
git branch -D [branchName] #强制删除本地分支
git push origin --delete [branchName] #删除远程分支
合并
git merge [branchName] #合并分支--将分支branchName和当前分支合并
提交
git push [remote] [branchName] #提交工作区 通常 remote指origin
拉取
git fetch [remote] #下载远程仓库的变化
git pull [remote] [branchName] #取回远程仓库的变化,并与本地分支合并
重命名
git branch -m [oldName] [newName]
追踪
git branch --set-upstream [branchName] origin/[branchName] #将本地分支与远程分支之间建立链接