導(dǎo)語
該文章主要參考于阮一峰的網(wǎng)絡(luò)日志,記錄一些常用的Git命令
配置Git
密鑰
ssh-keygen -t rsa -C 'yours@email.com'#生成密鑰
多賬號(hào)SSH配置
1.生成指定名字的密鑰
ssh-keygen -t rsa -C 'yours@email.com' -f ~/.ssh/git_test#生成git_test和git_test.pub文件
2.把密鑰復(fù)制到托管平臺(tái)(gitlab、github)
把git_test.pub內(nèi)容復(fù)制到代碼托管平臺(tái)
3.修改config文件
vim ~/.ssh/config#修改config文件,如果沒有創(chuàng)建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
修改個(gè)人信息
git config --global user.name "yourName"
git config --global user.email "yourEmail"
基本命令

- Workspace : 工作區(qū)
- Index/stage : 暫存區(qū)
- Repository : 工作區(qū)
- Remote : 工作區(qū)
新建倉(cāng)庫(kù)
git init [project-name] #新建目錄
git clone [url] #下載項(xiàng)目(ssh或者h(yuǎn)ttps)
文件操作
添加
git add [file1] [files] ···#添加指定文件到暫存區(qū)
git add #添加所有文件到暫存區(qū)
刪除
git rm [file1] [file2]···#刪除文件,并把刪除放入暫存區(qū)
提交
git commit -m [message] #提交暫存區(qū)到倉(cāng)庫(kù)區(qū)
git commit [file1] [file2]··· -m [message]#提交暫存區(qū)指定文件到倉(cāng)庫(kù)區(qū)
git commit -a #跳過暫存區(qū),把追蹤過的文件暫存起來一起提交
取消
git reset --hard #重置暫存和工作區(qū),與上次commit一致
git reset --hard [commit] #重置到指定狀態(tài),與[commit]一致
git reset [file] #重置暫存區(qū)的指定文件,與上次commit一致
git revert [commit] #撤銷指定commit
恢復(fù)
git checkout [file] #恢復(fù)暫存區(qū)的指定文件到工作區(qū)
git checkout [commit] [file] #恢復(fù)某個(gè)commit的指定文件到暫存區(qū)和工作區(qū)
git checkout#恢復(fù)暫存區(qū)的所有文件到工作區(qū)
查看
git status #顯示變更文件
git log #顯示當(dāng)前分支版本
git log --stat #顯示commit歷史,及每次commit變更文件
git blame [file] #顯示指定文件中的代碼的修改時(shí)間和人
git diff #顯示工作區(qū)和暫存區(qū)的區(qū)別
git diff --cached [file] #顯示暫存區(qū)和上一次commit的區(qū)別
git diff --shortstat #顯示今天寫了多少行代碼
git reflog #顯示當(dāng)前分支的最近幾次提交
分支操作
查看
git branch #查看所有本地分支
git branch -a #查看所有本地和遠(yuǎn)程分支
新建
git branch [branchName] #新建分支,但是仍停留在當(dāng)前分支
git checkout -b [branchName]#新建分支,并切換到該分支
切換
git checkout [branchName] #切換分支
git checkout - #切換到上次分支
刪除
git branch -d [branchName] #刪除本地分支
git branch -D [branchName] #強(qiáng)制刪除本地分支
git push origin --delete [branchName] #刪除遠(yuǎn)程分支
合并
git merge [branchName] #合并分支--將分支branchName和當(dāng)前分支合并
提交
git push [remote] [branchName] #提交工作區(qū) 通常 remote指origin
拉取
git fetch [remote] #下載遠(yuǎn)程倉(cāng)庫(kù)的變化
git pull [remote] [branchName] #取回遠(yuǎn)程倉(cāng)庫(kù)的變化,并與本地分支合并
重命名
git branch -m [oldName] [newName]
追蹤
git branch --set-upstream [branchName] origin/[branchName] #將本地分支與遠(yuǎn)程分支之間建立鏈接