一、說明
版本控制在軟體開發中非常重要,有了版本控制不但可以記錄軟體變動脈絡,還能多線開發、合併、摘取、回遡、差異比對等功能,在團隊合作中尤其重要。
二、安裝
2.1 Windows
下載並安裝 Git
基本上一直按「下一步」到底就可以了
驗證安裝(開啟新的 CMD 或 PowerShell):
1
2git --version
# 輸出範例:git version 2.42.0.windows.1Git 參數設定(與 Linux/macOS 相同):
1
2
3
4
5
6# 設定Git操作者的名字與信箱 (必要)
$ git config --global user.name {我的名字}
$ git config --global user.email {我的信箱}
# 編輯 git 時使用 VSCode 編輯器 (選項)
$ git config --global core.editor "code --wait"- **{我的名字}、{我的信箱}**替換成自己的英文名字和電子信箱
下載Git GUI管理軟體 TortoiseGit
下載主程式和語言包 (建議不裝中文,看習慣英文)
基本上設定個人資訊前一直按「下一步」就可以了
2.2 macOS
使用 Homebrew 安裝(推薦)
1
$ brew install git
驗證安裝:
1
2$ git --version
# 輸出範例:git version 2.42.0Git 參數設定(與 Linux 相同):
1
2
3
4
5
6
7
8# 設定Git操作者的名字與信箱 (必要)
$ git config --global user.name {我的名字}
$ git config --global user.email {我的信箱}
# 編輯 git 時使用 VSCode 編輯器 (選項,擇一)
$ git config --global core.editor "code --wait"
# 編輯 git 時使用 vim 編輯器 (選項,擇一)
$ git config --global core.editor vim- **{我的名字}、{我的信箱}**替換成自己的英文名字和電子信箱
2.3 Linux(Ubuntu 20.04/22.04 LTS)
安裝Git
1
$ sudo apt-get install git
驗證安裝:
1
2$ git --version
git version 2.x.xGit 參數設定
1
2
3
4
5
6
7
8# 設定Git操作者的名字與信箱 (必要)
$ git config --global user.name {我的名字}
$ git config --global user.email {我的信箱}
# 編輯 git 時使用 VSCode 編輯器 (選項,擇一)
$ git config --global core.editor "code --wait"
# 編輯 git 時使用 vim 編輯器 (選項,擇一)
$ git config --global core.editor vim- **{我的名字}、{我的信箱}**替換成自己的英文名字和電子信箱
三、SSH 金鑰設定(用於 GitHub/GitLab)
3.1 產生 SSH 金鑰
1 | # 產生 SSH 金鑰(使用您的 Email) |
3.2 複製公鑰
1 | # macOS/Linux |
3.3 新增至 GitHub/GitLab
- 登入 GitHub → Settings → SSH and GPG keys → New SSH key
- 貼上公鑰內容,儲存
- 測試連線:
1
2ssh -T git@github.com
# 成功訊息:Hi username! You've successfully authenticated...
四、常用指令
- 下載repository: git clone
<repo>
(repo格式:git@xxx.xx:xxx/xxx.git) - 查看記錄: git log
- 查看歷史記錄: git reflog
如果誤操作時,可用此找查之前的記錄
- 查看目前變動: git status
- 收藏變動: git stash
- 取出收藏: git stash pop
- 暫存變動: git add
<file>
- 暫存全部變動: git add -u
不含未處理過的檔案
- 暫存全部變動: git add .
含未處理過的檔案
- 暫存路徑變動: git add
<dir>
含未處理過的檔案
- 取消暫存變動: git reset HEAD
<file>
取消不小心 git add 的檔案
- 提交: git commit
- 推送至遠端: git push
強制推送: git push -f
- 獲取遠端記錄: git fetch
- 獲取並合併: git pull
<branch>
- 合併分支: git merge
<commit>
- 變基: git rebase -i
<commit>
- 切換分支: git checkout
<branch>
- 清除變動檔案: git checkout
<file>
- 清除分支所有變動: git checkout – .
- 變更工作目錄至commit: git reset
<commit>
只移動branch位置,不變動檔案
- 變更工作目錄至commit: git reset –hard
<commit>
移動branch位置,並重置檔案
- 建立新分支: git branch
- 建立tag: git tag
<tag>
- 推送tag: git push origin
<tag>
同等: git push origin refs/tags/
<tag>
- 刪除tag: git tag -d
<tag>
- 刪除遠端tag: git push origin refs/tags/
<tag>
必需先把本地tag刪除(推送空tag)