Git 初始化與設定檔 (config)

Git 初始化

git init

在專案的根目錄中執行上述指令後,Git 會產生一個名為 .git 的隱藏資料夾,該資料夾包含了 Git 所需的版本控制資訊與歷史紀錄。


Git 設定 (git config)

Git 提供三種設定層級,透過 --local--global--system 指定不同範圍的設定。

查看目前設定

git config --list

顯示所有目前套用的 Git 設定參數,包含各層級(local、global、system)的合併結果。


Local 設定(專案層級)

設定僅對目前專案的 Git 儲存庫生效,會寫入 .git/config 檔案中:

git config --local user.name "Your Name"
git config --local user.email "[email protected]"

Global 設定(使用者層級)

設定對該使用者帳號下的所有 Git 專案皆有效,會寫入:

  • Windows: %USERPROFILE%\.gitconfig
  • macOS/Linux: ~/.gitconfig
git config --global user.name "Your Name"
git config --global user.email "[email protected]"

System 設定(系統層級)

設定對該系統上的所有使用者有效,會寫入 /etc/gitconfig

git config --system user.name "Your Name"
git config --system user.email "[email protected]"

⚠️ 使用 --system 層級需具備系統管理員權限(如 sudo


移除使用者設定

可使用 --unset 移除指定層級的設定項目:

# Local
git config --local --unset user.name
git config --local --unset user.email

# Global
git config --global --unset user.name
git config --global --unset user.email

# System
git config --system --unset user.name
git config --system --unset user.email

忽略不需加入版本控制的檔案(.gitignore

使用 .gitignore 檔案可指定 Git 不應追蹤的檔案與資料夾。建立 .gitignore 並填入規則即可:

touch .gitignore

常見範例:

1. 忽略特定檔案

file.txt             # 忽略專案根目錄下的 file.txt
folder/file.txt      # 忽略 folder 資料夾中的 file.txt

2. 忽略特定副檔名的檔案

*.log                # 忽略所有 .log 檔案
*.tmp                # 忽略所有 .tmp 檔案

3. 忽略資料夾

folder/              # 忽略根目錄下的 folder 資料夾及其中所有內容

4. 忽略資料夾中的特定類型檔案

folder/*.tmp         # 忽略 folder 資料夾中的所有 .tmp 檔案

5. 忽略資料夾下所有內容(含子資料夾)

folder/*             # 忽略 folder 資料夾中所有內容(含子資料夾與檔案)

.gitignore 自身是 Git 可追蹤的檔案,若你不希望它被加入版本控制,也可以在另一個 .gitignore 中排除它(通常不建議這麼做,因為它本身是設定檔)。