Git 安裝與設定 (Installation & Configuration)
在開始使用 Git 之前,你需要先在電腦上安裝 Git 並進行基本設定。
安裝 Git
Windows
- 前往 Git 官方網站 下載安裝程式
- 執行安裝程式,大部分選項使用預設值即可
- 安裝完成後,你會有 Git Bash 可以使用
或者使用 winget 安裝:
winget install --id Git.Git -e --source winget
macOS
macOS 可能已經預裝了 Git,打開終端機輸入 git --version 檢查。
如果沒有安裝,可以用以下方式安裝:
使用 Homebrew(推薦):
brew install git
使用 Xcode Command Line Tools:
xcode-select --install
Linux
使用套件管理器安裝:
# Ubuntu / Debian
sudo apt update
sudo apt install git
# CentOS / Fedora
sudo dnf install git
# Arch Linux
sudo pacman -S git
確認安裝成功
打開終端機,輸入:
git --version
如果看到類似 git version 2.43.0 的版本號,表示安裝成功。
基本設定
安裝完 Git 後,第一件事就是設定你的使用者名稱和 Email,這些資訊會記錄在每次的 commit 中:
git config --global user.name "你的名字"
git config --global user.email "你的email@example.com"
例如:
git config --global user.name "Mike Lee"
git config --global user.email "mike@example.com"
--global 表示這是全域設定,會套用到你電腦上所有的 Git 專案。
查看設定
查看所有設定:
git config --list
查看特定設定:
git config user.name
git config user.email
設定預設編輯器
Git 在需要你輸入訊息時(例如 commit message)會開啟編輯器,預設通常是 Vim。
如果你不熟悉 Vim,可以改用其他編輯器:
# 使用 VS Code
git config --global core.editor "code --wait"
# 使用 Nano
git config --global core.editor "nano"
# 使用 Notepad++ (Windows)
git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
設定預設分支名稱
Git 新版本建議將預設分支名稱從 master 改為 main:
git config --global init.defaultBranch main
設定換行符號
不同作業系統使用不同的換行符號,這可能會造成跨平台協作的問題:
# Windows
git config --global core.autocrlf true
# macOS / Linux
git config --global core.autocrlf input
設定檔位置
Git 的設定分為三個層級:
- 系統層級 (
/etc/gitconfig):套用到所有使用者 - 使用者層級 (
~/.gitconfig):套用到當前使用者的所有專案 - 專案層級 (
.git/config):只套用到該專案
使用 --global 是設定使用者層級,如果要針對特定專案設定,在專案目錄下執行不加 --global 的指令即可。
設定別名
你可以為常用的指令設定簡短的別名:
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.lg "log --oneline --graph --all"
設定後就可以用簡短的指令:
git co main # 等同於 git checkout main
git br # 等同於 git branch
git ci -m "msg" # 等同於 git commit -m "msg"
git st # 等同於 git status
git lg # 漂亮的 log 顯示