1. 配置
# 配置本倉庫
git config --local
# 配置所有倉庫
git config --global
# 配置登陸用戶所有的所有倉庫
git config --system
# 示例
git config --global user.name 'test'
git config --global user.email 'test@test.com'
# 查看配置乞旦,可指定環(huán)境
git config --list --local/global/system
2. 初始化倉庫
# 新建項(xiàng)目
git init new_project
# 已有項(xiàng)目
cd project
git init
3. 提交更改
# 添加文件到暫存區(qū)
git add file
# 添加目錄
git add directory
# 組合
git add file1 file2 directory1 directory2
# 添加所有
git add .
# 提交
git commit -m '注釋'
# 快捷方式:添加 + 提交
git commit -am '注釋'
4. 查看日志
# 默認(rèn)
git log
# 簡(jiǎn)潔
git log --oneline
# 最近提交的5個(gè)日志
git log -n5
# 所有分支
git log --all
# 圖形化
git log --graph
# 組合
git log --all --graph -n10 --oneline
5. 查看變更
# 有哪些變更
git status
# 工作區(qū) vs. 暫存區(qū)
git diff
git diff -- file
# 暫存區(qū) vs. HEAD
git diff --cached
# 兩個(gè)提交字間的對(duì)比
git diff commit1_hash commit2_hash
# 利用快捷方式
git diff HEAD HEAD^1
git diff HEAD HEAD~1
git diff HEAD HEAD^1^1
git diff HEAD HEAD~2
6. 回滾
# 將暫存區(qū)回滾到與HEAD一致
git reset HEAD
git reset HEAD -- file1 file2
# 將工作區(qū)回滾到與暫存區(qū)一致
git checkout
git checkout -- file1 file2
# 回滾整個(gè)工作區(qū)和暫存區(qū)到HEAD
git reset HEAD --hard
# 回滾到某個(gè)提交
git reset hash --hard
7. 修改提交
# 修改最近一次提交的注釋
git commit --amend
# 整理本地的commits溉箕,支持修改注釋胸完、合并提交等
git rebase -i
8. 暫存
# 暫存肢娘,可執(zhí)行多次
git stash
# 查看暫存了幾次
git stash list
# 應(yīng)用暫存到當(dāng)前工作區(qū)
git stash apply
# 應(yīng)用暫存到當(dāng)前工作區(qū),并清除暫存
git stash pop
9. 遠(yuǎn)端倉庫
# 盡量使用帶協(xié)議的方式
git clone file:///path/top/repo.git
git clone https://git-server.com:port/path/to/repo.git
# 不帶工作區(qū)
git clone --bare file:///path/top/repo/.git rep.git
# 查看遠(yuǎn)程倉庫
git remote -v
# 設(shè)置遠(yuǎn)程倉庫
git remote add rep file:///path/top/repo.git
# 設(shè)置遠(yuǎn)端分支
git push --set-upstream
# push branch and tags
git push remote --all
# push only tags
git push remote --tags
# only fetch
git fetch remote
# fetch and merge
git pull remote
10. 分支管理
# 創(chuàng)建并切換到新分支
git checkout -b new_branch
git checkout -b local_branch remote_branch
# 列出本地分支
git branch -v
# 包含遠(yuǎn)端分支
git branch -av
# 如果沒有merge译隘,會(huì)報(bào)錯(cuò)
git branch -d
# 強(qiáng)制刪除
git branch -D
11. merge vs. rebase
11.1 merge
git.merge.png
# merge 流程
git checkout experiment
git merge master
11.2 rebase
git.rebase.png
提取在
C4
中引入的補(bǔ)丁和修改丛肮,然后在 C3
的基礎(chǔ)上重新應(yīng)用一次轩娶。在 Git 中,這種操作就叫做 變基(
rebase
)沾凄。如圖梗醇,因?yàn)榛€變了,所以叫
rebase
變基撒蟀。
git checkout experiment
git rebase master
git checkout master
git merge experiment # 應(yīng)為fast-forward
11.3 rebase的風(fēng)險(xiǎn)
不要再公共分支上(比如master)使用
rebase
叙谨,否則會(huì)遭到團(tuán)隊(duì)成員的唾棄!
因?yàn)楸M停卜种系?變基
手负,可能導(dǎo)致其他團(tuán)隊(duì)成員的基
不在公共分支上,從而導(dǎo)致代碼重復(fù)合并姑尺。
看下圖
git.rebase.risk.png
如果確實(shí)發(fā)生了竟终,那就只能找到原因,然后用變基來解決變基
切蟋。
git.rebase.rebase.png
git checkout master
git pull --rebase
12. 其他
#查看類型
git cat-file -t hash
#查看內(nèi)容
git cat-file -p hash
# 刪除文件
git rm file
# 重命名文件
git mv file1 file2
# 強(qiáng)行push统捶,慎用
git push -f remote branch