Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Git 與遠端倉庫實戰指南:從初始化到分支管理、回滾與協作

編輯:Linux 系統常見問題解答

核心工作流

  1. 在程式碼託管平台(Bitbucket/GitHub/GitLab)建立空倉庫。
  2. 本地初始化專案並提交基礎代碼。
  3. 建立功能分支開發,完成後合併或捨棄。
  4. 推送至遠端倉庫,或在另一台機器克隆協作。

安裝 Git

  • Linux/macOS:通常預裝,更新:git clone https://github.com/git/git(不建議生產環境編譯安裝)。
  • Windows:下載 Git for Windows 安裝包。

建立遠端倉庫(以 Bitbucket 為例)

  1. 註冊/登入 Bitbucket。
  2. 點擊「Create repository」,填寫名稱,勾選「Private repository」。
  3. 獲得倉庫 URL:https://your_username@bitbucket.org/your_username/repo_name.git

本地 Git 初始配置

git config --global user.name "your_username"
git config --global user.email "your_email@domain.com"
git config --global push.default simple  # 推送預設行為:僅推送當前分支至同名上游

初始化本地倉庫與首次提交

cd ~/workspace/my_project
git init
git add .                    # 暫存所有檔案
git commit -m "initial commit"  # 首次提交
git status                   # 查看狀態

分支管理實戰

建立與切換分支

git checkout -b new_feature   # 建立並切換
# 或分兩步
git branch new_feature
git checkout new_feature

查看分支

git branch        # 本地分支
git branch -a     # 含遠端分支

合併分支(功能完成)

git add .
git commit -m "adds new feature"
git checkout master
git merge new_feature

捨棄分支(功能放棄)

git add .
git commit -m "discard feature"
git checkout master
# 分支內容已回到建立前狀態

刪除分支

git branch -d new_feature      # 已合併才能刪
git branch -D new_feature      # 強制刪除未合併分支

版本回滾

git log                      # 查看提交歷史
git checkout      # 暫時切換到舊版本(分離 HEAD 狀態)
git checkout -b old_version   # 基於舊版本建新分支

遠端協作

首次推送

git remote add origin https://your_username@bitbucket.org/your_username/repo_name.git
git push origin master

克隆遠端倉庫

cd ~/workspace
git clone https://your_username@bitbucket.org/your_username/repo_name.git

拉取更新

cd repo_name
git pull origin master

實用別名配置

git config --global alias.c 'commit -m'
git config --global alias.co 'checkout'
git config --global alias.br 'branch'
git config --global alias.st 'status'
git config --global alias.lg "log --oneline --graph --all"

總結

掌握 Git 核心工作流與分支策略,能讓個人或團隊開發更有序、可追溯。建議養成「小步提交、頻繁推送、善用分支」的習慣,並熟悉 rebase、cherry-pick、stash 等進階指令應對複雜場景。

Copyright © Windows教程網 All Rights Reserved