Git 教學
安裝篇
下載Git
- 安裝過程 next下一步到底。
- 安裝完成之後,可以找到 「Git Bash」
檢查是否安裝成功1
$ git --version
設定篇
建立目錄讓Git管理
1 | $ git init |
設定ssh key
查看ssh key
1 | $ ls -al ~/.ssh |
一般預設的公共密鑰文件為下列其中之一:
- id_dsa.pub
- id_ecdsa.pub
- id_ed25519.pub
- id_rsa.pub
產生ssh key
1 | $ ssh-keygen -t rsa -b 4096 -C "GitHub email address" |
設定 SSH Key 密碼
複製ssh key
1 | $ cat ~/.ssh/id_rsa.pub | pbcopy |
測試ssh
1 | $ ssh -T git@github.com |
使用者設定
設定使用者的名稱與電子信箱,不然每次commit都要輸入一次。1
2$ git config --global user.name "UserName"
$ git config --global user.email "UserName@email.com"
查看git config 設定1
$ git config --list
進階用法:不同的專案設定不同的作者
a.切到該專案目錄1
2$ git config --local user.name "UserName"
$ git config --local user.email "UserName@email.com"
c.設定之後這個專案目錄就會跑local的設定檔,離開這個專案還是會跑Global。
更換編輯器: vim -> emacs
1 | $ git config --global core.editor emacs |
自訂指令:Alias 別名
1 | $ git config --global alias.l log |
設定之後,輸入 git l 指令就跟 git log 一樣。
設定之後,輸入 git lg 指令就跟 git log --oneline --graph 一樣。
基礎篇
建立 Git 專案
1 | $ git init |
提交一個 Patch
1 | $ git status |
新增 / 修改檔案
1 | $ git diff |
刪除檔案
1 | $ git rm <file> |
搬移檔案
1 | $ git mv <file> <directory> |
重新命名檔案
1 | $ git mv <file> <new_name> |
檔案狀態
1 | $ git reset HEAD |
檔案還原
1 | $ git checkout -- <file> |
忽略檔案 .gitignore
1 | $ git add -f <file> |
提交空白Patch
1 | $ git commit --allow-empty -m "空的" |
Patch篇
基本觀念
1 | $ git log --pretty=raw |
關鍵字 HEAD
1 | $ git show HEAD^ |
Reset Patch
1 | $ git log --oneline |
找回消失的 Patch
1 | $ git reflog |
修改 / 訂正 Patch
1 | $ git commit --amend |
移除單一個 Patch
1 | $ git cherry-pick <commit id> |
Rebase 互動模式
1 | $ git rebase -i <after this commit> |
Cherry-Pick 版本衝突
1 | $ git cherry-pick --continue |
Rebase 版本衝突
1 | $ git rebase --continue |
Revert Patch
1 | $ git revert <commit id> |
分支篇
查看分支
1 | $ git branch |
建立 / 刪除分支
1 | $ git branch <new branch name> |
Commit Tree
1 | $ git checkout <commit id> |
Rebase 合併分支
1 | $ git cherry-pick <commit 1> <commit 2> ... |
Merge 合併分支
1 | $ git merge <branch name> |
遠端篇
新增專案
1 | ssh-keygen -t rsa |
設定 Repo URL
1 | $ git remote -v |
上傳分支
1 | $ git branch -a |
設定 Upstream
1 | $ git push -u <remote name> <branch name> |
複製 / 下載專案
1 | $ git clone <repo URL> |
同步遠端分支
1 | $ git fetch <remote name> |
強制更新遠端分支
1 | $ git push -f |
刪除遠端分支
1 | $ git push <remote name> :<branch name> |
進階篇
檔案暫存
1 | $ git stash |
Add / Checkout 檔案部分內容
1 | $ git add -p |
版本標籤
1 | $ git tag |
子模組
1 | $ git submodule init |
心得
每次git commit都會產生一個Patch,
git rebase 整理Patch會改變Hush值
git reset https://git-scm.com/book/en/v2/Git-Tools-Reset-Demystified.
- 移動HEAD分支的指向
git reset --soft只是移動HEAD
- 使索引看起來像HEAD
git reset --mixed移動HEAD,還原Stage區
- 使工作目錄看起來像索引
git reset --hard移動HEAD,….還原工作目錄