定閱客戶

2025年7月16日 星期三

Git 快速教學:核心概念與常用指令

什麼是 Git?

Git 是一個版本控制系統,幫助你追蹤程式碼的變更、協作開發,並在需要時回溯到之前的版本。它廣泛應用於軟體開發。

事前準備

  1. 安裝 Git
  2. 下載並安裝 Git:https://git-scm.com/
  3. 確認安裝:在終端機輸入 git --version,檢查是否有版本號輸出。
  4. 設置基本資訊bash git config --global user.name "你的名字" git config --global user.email "你的電子郵件" 這會告訴 Git 你的身份,方便在提交時記錄。

Git 核心工作流程

1. 初始化與基本操作

  • 創建新倉庫bash git init 在當前資料夾初始化一個新的 Git 倉庫,會生成一個 .git 隱藏資料夾。
  • 檢查狀態bash git status 查看當前倉庫的狀態(哪些檔案被修改、待提交等)。
  • 添加檔案到暫存區bash git add 文件名 git add . # 添加所有變更的檔案
  • 提交變更bash git commit -m "提交訊息" 將暫存區的變更儲存到倉庫,提交訊息應簡潔描述變更內容。

2. 查看歷史與回溯

  • 查看提交歷史bash git log git log --oneline # 簡潔版顯示 查看所有的提交記錄,每個提交有唯一的 commit ID
  • 回溯到某個版本bash git checkout <commit-id> # 切換到特定提交 git checkout main # 回到主分支
  • 還原變更bash git restore 文件名 # 放棄未暫存的修改 git restore --staged 文件名 # 取消已暫存的檔案 git reset HEAD^ # 回退最後一次提交(保留變更)

3. 分支管理

分支是 Git 的強大功能,允許多人並行開發或嘗試新功能。

  • 創建分支bash git branch 分支名稱
  • 切換分支bash git checkout 分支名稱 git switch 分支名稱 # 較新指令
  • 創建並切換分支bash git checkout -b 分支名稱 git switch -c 分支名稱
  • 合併分支bash git checkout main # 先切換到目標分支 git merge 分支名稱 # 將指定分支合併到當前分支
  • 刪除分支bash git branch -d 分支名稱

4. 遠端倉庫操作

Git 通常與遠端倉庫(如 GitHub、GitLab)配合使用。

  • 連接到遠端倉庫bash git remote add origin <遠端倉庫 URL>
  • 推送本地變更到遠端bash git push origin 分支名稱
  • 拉取遠端變更bash git pull origin 分支名稱
  • 克隆遠端倉庫bash git clone <遠端倉庫 URL>

5. 解決衝突

當多人修改同一檔案時,可能發生合併衝突: 1. 執行 git mergegit pull 時,Git 會提示衝突。 2. 打開衝突檔案,手動修改標記為 <<<<<<<>>>>>>> 的部分。 3. 修改完成後,執行: bash git add 衝突檔案 git commit

實用技巧

  • 快速提交bash git commit -am "提交訊息" # 直接添加並提交已追蹤的檔案
  • 查看變更差異bash git diff # 查看未暫存的變更 git diff --staged # 查看已暫存的變更
  • 暫存未完成工作bash git stash # 暫存當前變更 git stash pop # 恢復暫存的變更
  • 忽略檔案: 創建 .gitignore 檔案,列出不想追蹤的檔案或資料夾,例如: node_modules/ *.log

常見情境範例

  1. 開始一個新專案bash git init git add . git commit -m "初次提交" git remote add origin <URL> git push origin main
  2. 開發新功能bash git checkout -b feature-新功能 # 編輯檔案 git add . git commit -m "完成新功能" git checkout main git merge feature-新功能 git push origin main
  3. 修復 Bugbash git checkout -b fix-bug # 修復檔案 git add . git commit -m "修復 Bug" git checkout main git merge fix-bug

注意事項

  • 提交訊息要清晰:寫出有意義的訊息,例如「修復登錄頁面錯誤」而非「更新」。
  • 頻繁提交:小而頻繁的提交更容易管理。
  • 備份到遠端:定期推送至 GitHub 等平台,避免資料遺失。
  • 小心使用 git reset --hard:這會永久刪除變更,謹慎操作。

進階學習資源

  • 官方文件:https://git-scm.com/doc
  • 互動學習:https://learngitbranching.js.org/
  • GitHub 指南:https://guides.github.com/

 

沒有留言: