1. 初期設定と構成

Gitを使い始める前に、ユーザー情報やエディタ設定などの初期設定が必要です。 Gitの設定には3つのレベルがあります:system(システム全体)、global(ユーザー単位)、local(リポジトリ単位)。

ユーザー情報の設定

コミット時に記録される名前とメールアドレスを設定します。この設定は必須です。

グローバル設定(すべてのリポジトリで使用)

# 名前を設定
git config --global user.name "あなたの名前"

# メールアドレスを設定
git config --global user.email "your.email@example.com"

ローカル設定(特定のリポジトリのみ)

# 仕事用と個人用でメールアドレスを分ける場合など
git config --local user.name "仕事用の名前"
git config --local user.email "work@company.com"

エディタの設定

コミットメッセージやマージ編集時に使用するテキストエディタを指定します。

# Vimを使用
git config --global core.editor "vim"

# VS Codeを使用
git config --global core.editor "code --wait"

# Nanoを使用
git config --global core.editor "nano"

# Emacsを使用
git config --global core.editor "emacs"

# Sublime Textを使用
git config --global core.editor "subl -n -w"

diffとmergeツールの設定

差分表示やマージに使用する外部ツールを設定できます。

# vimdiffをdiffツールとして設定
git config --global diff.tool vimdiff

# vimdiffをmergeツールとして設定
git config --global merge.tool vimdiff

# VS Codeをdiffツールとして設定
git config --global diff.tool vscode
git config --global difftool.vscode.cmd 'code --wait --diff $LOCAL $REMOTE'

# ツール起動時の確認プロンプトを無効化
git config --global difftool.prompt false

エイリアスの設定

よく使うコマンドにエイリアス(短縮名)を設定することで、作業効率が向上します。

基本的なエイリアス

# statusをstで実行
git config --global alias.st status

# checkoutをcoで実行
git config --global alias.co checkout

# branchをbrで実行
git config --global alias.br branch

# commitをciで実行
git config --global alias.ci commit

便利なエイリアス

# 見やすいログ表示
git config --global alias.lg "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"

# 最後のコミットを表示
git config --global alias.last 'log -1 HEAD'

# 変更を一括ステージング
git config --global alias.aa 'add --all'

# ステージングを取り消し
git config --global alias.unstage 'reset HEAD --'

# 削除されたリモートブランチをローカルからも削除
git config --global alias.prune-branches 'remote prune origin'

# マージ済みローカルブランチを一括削除
git config --global alias.delete-merged-branches '!git branch --merged | grep -v \"\\*\" | grep -v \"main\" | grep -v \"master\" | xargs -n 1 git branch -d'

設定の確認と一覧表示

現在の設定値を確認するコマンドです。

# すべての設定を表示
git config --list

# 設定とそのファイルの場所を表示
git config --list --show-origin

# 特定の設定値を確認
git config user.name
git config user.email

# グローバル設定のみ表示
git config --global --list

# ローカル設定のみ表示
git config --local --list

設定の編集と削除

設定ファイルを直接編集したり、設定を削除したりできます。

# グローバル設定ファイルをエディタで開く
git config --global --edit

# ローカル設定ファイルをエディタで開く
git config --local --edit

# 特定の設定を削除
git config --global --unset user.name

# エイリアスを削除
git config --global --unset alias.st

# セクションごと削除
git config --global --remove-section alias

その他の便利な設定

開発効率や視認性を向上させる推奨設定です。

カラー表示

# コマンド出力に色を付ける
git config --global color.ui auto

# ブランチ名に色を付ける
git config --global color.branch auto

# diffに色を付ける
git config --global color.diff auto

# statusに色を付ける
git config --global color.status auto

行末文字の設定

# Windowsでチェックアウト時にCRLF、コミット時にLFに変換
git config --global core.autocrlf true

# macOS/Linuxでチェックアウト時は変換せず、コミット時にLFに変換
git config --global core.autocrlf input

pushのデフォルト動作

# 現在のブランチのみをpush(推奨)
git config --global push.default simple

# 上流ブランチを自動設定
git config --global push.autoSetupRemote true

pullのデフォルト動作

# pull時にrebaseを使用(履歴が綺麗に保たれる)
git config --global pull.rebase true

# pull時にmergeを使用(デフォルト)
git config --global pull.rebase false

# fast-forwardのみ許可
git config --global pull.ff only

キャッシュとパフォーマンス

# 認証情報をキャッシュ(秒単位)
git config --global credential.helper 'cache --timeout=3600'

# macOSでKeychainを使用
git config --global credential.helper osxkeychain

# WindowsでCredential Managerを使用
git config --global credential.helper manager

# ファイルシステムのキャッシュを有効化
git config --global core.preloadindex true
git config --global core.fscache true

デフォルトブランチ名

# 新規リポジトリのデフォルトブランチをmainに設定
git config --global init.defaultBranch main

条件付き設定(includeIf)

ディレクトリごとに異なる設定を適用できます。仕事用と個人用でメールアドレスを切り替える場合などに便利です。

~/.gitconfigの設定例

# デフォルト設定(個人用)
[user]
    name = Your Name
    email = personal@example.com

# ~/work/以下のリポジトリでは仕事用設定を適用
[includeIf "gitdir:~/work/"]
    path = ~/.gitconfig-work

# ~/personal/以下のリポジトリでは個人用設定を明示的に適用
[includeIf "gitdir:~/personal/"]
    path = ~/.gitconfig-personal

~/.gitconfig-workの内容例

[user]
    name = Your Work Name
    email = work@company.com
    signingkey = WORK_GPG_KEY_ID

[core]
    sshCommand = ssh -i ~/.ssh/id_rsa_work

GPG署名付きコミットの設定

コミットにGPG署名を付けて、作成者の信頼性を高めることができます。GitHubでは署名付きコミットに"Verified"バッジが表示されます。

GPGキーの生成と設定

# GPGキーを生成(初回のみ)
gpg --full-generate-key

# 作成したGPGキーIDを確認
gpg --list-secret-keys --keyid-format=long

# GPGキーIDをGitに設定
git config --global user.signingkey YOUR_GPG_KEY_ID

# すべてのコミットに署名を付ける
git config --global commit.gpgsign true

# すべてのタグに署名を付ける
git config --global tag.gpgsign true

署名付きコミットの作成

# -Sオプションで署名付きコミット
git commit -S -m "署名付きコミット"

# グローバル設定でcommit.gpgsign=trueにしている場合は-S不要
git commit -m "自動的に署名される"

# 署名の確認
git log --show-signature

プロキシ設定

企業環境などでプロキシ経由でGitを使用する場合の設定です。

# HTTPプロキシの設定
git config --global http.proxy http://proxy.example.com:8080

# HTTPSプロキシの設定
git config --global https.proxy https://proxy.example.com:8080

# 認証付きプロキシ
git config --global http.proxy http://username:password@proxy.example.com:8080

# 特定のドメインのみプロキシを使用
git config --global http.https://github.com.proxy http://proxy.example.com:8080

# プロキシ設定を削除
git config --global --unset http.proxy
git config --global --unset https.proxy

rerere(再利用可能なマージ解決)の設定

rerere(reuse recorded resolution)を有効にすると、一度解決したコンフリクトの解決方法を記憶し、同じコンフリクトが発生したときに自動的に適用します。

# rerereを有効化
git config --global rerere.enabled true

# rerereのキャッシュを自動更新
git config --global rerere.autoupdate true

設定レベルの優先順位

Gitの設定には3つのレベルがあり、以下の優先順位で適用されます:

  1. local(最優先): .git/config - 特定のリポジトリのみ
  2. global: ~/.gitconfig または ~/.config/git/config - ユーザー全体
  3. system(最低): /etc/gitconfig - システム全体

同じ設定項目が複数のレベルで存在する場合、localが最も優先されます。

設定ファイルの場所

各レベルの設定ファイルの場所を知っておくと、直接編集する際に便利です。

# Systemレベル(Linux/macOS)
/etc/gitconfig

# Globalレベル
~/.gitconfig
~/.config/git/config  # 代替場所

# Localレベル(各リポジトリ内)
.git/config

# 設定ファイルの場所を確認
git config --list --show-origin

2. リポジトリの作成とクローン

Gitリポジトリを新規作成するか、既存のリモートリポジトリをクローンする方法を解説します。 プロジェクトを始める際の最初のステップです。

新規リポジトリの作成(git init)

既存のディレクトリをGitリポジトリとして初期化したり、新しいディレクトリを作成してリポジトリ化します。

基本的な使い方

# 現在のディレクトリをGitリポジトリとして初期化
git init

# 新しいディレクトリを作成してGitリポジトリとして初期化
git init my-project

# 特定のブランチ名で初期化(mainブランチで開始)
git init --initial-branch=main
git init -b main  # 短縮形

ベアリポジトリの作成

# ベアリポジトリを作成(作業ツリーなし、サーバー用)
git init --bare my-repo.git

# 共有リポジトリとして作成(グループで共有する場合)
git init --bare --shared=group my-repo.git

リポジトリのクローン(git clone)

リモートリポジトリをローカルにコピーします。GitHubなどのホスティングサービスからプロジェクトを取得する際に使用します。

基本的なクローン

# HTTPSでクローン
git clone https://github.com/username/repository.git

# SSHでクローン(推奨)
git clone git@github.com:username/repository.git

# 特定のディレクトリ名でクローン
git clone https://github.com/username/repository.git my-project

# カレントディレクトリにクローン(ディレクトリ名を付けない)
git clone https://github.com/username/repository.git .

特定のブランチをクローン

# 特定のブランチのみをクローン
git clone -b develop https://github.com/username/repository.git

# 特定のタグをクローン
git clone -b v1.0.0 https://github.com/username/repository.git

シャロークローン(Shallow Clone)

履歴の一部のみを取得することで、クローンを高速化し、ディスク容量を節約できます。 大規模リポジトリや CI/CD 環境で有用です。

# 最新の1コミットのみをクローン(最も高速)
git clone --depth 1 https://github.com/username/repository.git

# 最新の10コミットのみをクローン
git clone --depth 10 https://github.com/username/repository.git

# 特定のブランチをシャロークローン
git clone --depth 1 -b main https://github.com/username/repository.git

# シャロークローンを通常のクローンに変換(全履歴を取得)
git fetch --unshallow

部分クローン(Partial Clone)

Git 2.19以降で利用可能な機能で、必要なオブジェクトのみを取得します。 大規模なバイナリファイルを含むリポジトリで有用です。

# blobsを除外してクローン(ファイルの内容は必要時に取得)
git clone --filter=blob:none https://github.com/username/repository.git

# 大きなblobsを除外(例:1MB以上)
git clone --filter=blob:limit=1m https://github.com/username/repository.git

# treeオブジェクトのみ取得(ファイルとblobsは必要時に取得)
git clone --filter=tree:0 https://github.com/username/repository.git

サブモジュールを含むクローン

リポジトリがサブモジュールを含む場合の取得方法です。

# サブモジュールを含めてクローン
git clone --recurse-submodules https://github.com/username/repository.git

# サブモジュールも浅くクローン
git clone --recurse-submodules --shallow-submodules https://github.com/username/repository.git

# クローン後にサブモジュールを初期化・更新
git clone https://github.com/username/repository.git
cd repository
git submodule update --init --recursive

クローンのオプション

その他の便利なクローンオプションです。

# ミラークローン(全てのブランチとタグを取得)
git clone --mirror https://github.com/username/repository.git

# ベアリポジトリとしてクローン
git clone --bare https://github.com/username/repository.git

# 静かにクローン(進捗を表示しない)
git clone --quiet https://github.com/username/repository.git

# 詳細な進捗を表示
git clone --verbose https://github.com/username/repository.git

# 特定のリモート名でクローン(デフォルトはorigin)
git clone --origin upstream https://github.com/username/repository.git

既存のリポジトリから新規リポジトリを作成

既存のリポジトリをベースに、履歴を保持したまま新しいリポジトリを作成する方法です。

# 既存リポジトリをクローンして新リポジトリを作成
git clone https://github.com/username/old-repo.git new-repo
cd new-repo

# リモートを削除して新しいリモートを設定
git remote remove origin
git remote add origin https://github.com/username/new-repo.git

# 最初のプッシュ
git push -u origin main

.gitディレクトリの構造

git initまたはgit cloneを実行すると、.gitディレクトリが作成されます。 このディレクトリにはリポジトリの全情報が格納されています。

# .gitディレクトリの主な構造
.git/
├── config           # リポジトリ固有の設定
├── description      # リポジトリの説明
├── HEAD             # 現在のブランチへの参照
├── hooks/           # Git Hooksスクリプト
├── info/            # 除外ファイルなど
│   └── exclude      # .gitignoreの代替
├── objects/         # 全オブジェクト(commits, trees, blobs)
├── refs/            # ブランチとタグの参照
│   ├── heads/       # ローカルブランチ
│   ├── remotes/     # リモートブランチ
│   └── tags/        # タグ
├── logs/            # 参照ログ(reflog)
└── index            # ステージングエリア

リポジトリの状態確認

リポジトリが正しく初期化・クローンされたか確認する方法です。

# Gitリポジトリかどうか確認
git rev-parse --is-inside-work-tree

# リポジトリのルートディレクトリを表示
git rev-parse --show-toplevel

# .gitディレクトリの場所を表示
git rev-parse --git-dir

# 現在のブランチを確認
git branch --show-current

# リモートリポジトリの情報を確認
git remote -v

# リポジトリの設定を確認
git config --local --list

リポジトリの移行とバックアップ

リポジトリを別の場所に移動したり、バックアップを作成する方法です。

完全バックアップの作成

# ミラークローンでバックアップ(全ブランチ・タグ・設定を含む)
git clone --mirror https://github.com/username/repository.git repository-backup.git

# バックアップから復元
git clone repository-backup.git restored-repository

リポジトリのアーカイブ

# 特定のコミット時点のファイルをアーカイブ
git archive --format=zip --output=backup.zip HEAD

# 特定のブランチをアーカイブ
git archive --format=tar.gz --output=backup.tar.gz main

# 特定のタグをアーカイブ
git archive --format=zip --output=v1.0.0.zip v1.0.0

テンプレートを使用したリポジトリ初期化

カスタムテンプレートを使用してリポジトリを初期化できます。 チーム全体で統一されたGit設定を適用する際に便利です。

# テンプレートディレクトリを指定して初期化
git init --template=/path/to/template my-project

# グローバルなテンプレートディレクトリを設定
git config --global init.templateDir /path/to/template

# テンプレートディレクトリの構造例
/path/to/template/
├── hooks/
│   ├── pre-commit
│   └── post-merge
├── info/
│   └── exclude
└── description

クローン時のトラブルシューティング

クローン時によくある問題と解決方法です。

# SSL証明書の検証エラー(一時的な回避策)
git -c http.sslVerify=false clone https://github.com/username/repository.git

# タイムアウト時間を延長
git clone --config http.postBuffer=524288000 https://github.com/username/repository.git

# プロキシ経由でクローン
git clone --config http.proxy=http://proxy:port https://github.com/username/repository.git

# 認証情報を含むURL(非推奨、セキュリティリスクあり)
git clone https://username:password@github.com/username/repository.git

3. 基本的なワークフロー

Gitの日常的な作業で最も頻繁に使用するコマンド群です。 ファイルの状態確認、変更のステージング、コミットの作成など、 基本的なワークフローをマスターしましょう。

Gitの3つの領域

Gitでは、ファイルの変更を管理するために3つの主要な領域があります:

  1. 作業ディレクトリ(Working Directory): ファイルを編集する実際のディレクトリ
  2. ステージングエリア(Staging Area / Index): 次のコミットに含める変更を準備する領域
  3. リポジトリ(Repository): コミットされた変更の履歴が保存される領域

作業状態の確認(git status)

リポジトリの現在の状態を確認するために最も頻繁に使用するコマンドです。 変更されたファイル、ステージングされたファイル、未追跡のファイルなどを表示します。

基本的な使い方

# 詳細な状態表示(デフォルト)
git status

# 簡潔な状態表示
git status -s
git status --short

# ブランチ情報も含めて簡潔に表示
git status -sb

出力の見方

# 簡潔表示(-s)の記号の意味
??  # 未追跡(Untracked)
A   # 追加(Added)
M   # 変更(Modified)
D   # 削除(Deleted)
R   # リネーム(Renamed)
C   # コピー(Copied)
U   # 更新未マージ(Updated but unmerged)

# 左側の列: ステージングエリアの状態
# 右側の列: 作業ディレクトリの状態

# 例
 M file.txt    # ステージング済み、作業ディレクトリは変更なし
 M file.txt    # ステージングされていない変更
MM file.txt    # ステージング後、さらに作業ディレクトリで変更

その他のオプション

# 無視されたファイルも表示
git status --ignored

# 未追跡ファイルを表示しない
git status -uno
git status --untracked-files=no

# すべての未追跡ファイルを表示(サブディレクトリ含む)
git status -uall

変更のステージング(git add)

作業ディレクトリの変更をステージングエリアに追加します。 ステージングされた変更は、次のコミットに含まれます。

基本的な使い方

# 特定のファイルをステージング
git add file.txt

# 複数のファイルをステージング
git add file1.txt file2.txt file3.txt

# カレントディレクトリの全ファイルをステージング
git add .

# リポジトリ全体の全ファイルをステージング(削除も含む)
git add -A
git add --all

# 変更と削除のみステージング(新規ファイルは除外)
git add -u
git add --update

パターンマッチング

# ワイルドカードを使用
git add *.txt          # 全てのtxtファイル
git add src/*.js       # srcディレクトリの全てのjsファイル
git add "*.txt"        # サブディレクトリを含む全てのtxtファイル

# 特定のディレクトリ全体
git add src/
git add docs/

インタラクティブモード

# インタラクティブモードで対話的にステージング
git add -i
git add --interactive

# パッチモード(変更の一部のみをステージング)
git add -p
git add --patch

# パッチモードの操作
# y - このハンクをステージング
# n - このハンクをスキップ
# q - 終了
# a - このファイルの残り全てをステージング
# d - このファイルの残り全てをスキップ
# s - ハンクを分割
# e - 手動で編集

強制追加

# .gitignoreで無視されているファイルも強制的に追加
git add -f ignored-file.txt
git add --force ignored-file.txt

ドライラン

# 実際には追加せず、何が追加されるか確認
git add -n .
git add --dry-run .

コミットの作成(git commit)

ステージングエリアの変更をリポジトリに永続的に記録します。 コミットには説明的なメッセージを付けることが重要です。

基本的な使い方

# エディタを開いてコミットメッセージを入力
git commit

# コマンドラインでメッセージを指定
git commit -m "コミットメッセージ"

# 複数行のメッセージ
git commit -m "要約行" -m "詳細な説明"

# ステージングとコミットを同時実行(追跡済みファイルのみ)
git commit -a -m "メッセージ"
git commit -am "メッセージ"

コミットメッセージのベストプラクティス

# 推奨される形式
# 1行目: 50文字以内の要約(命令形で記述)
# 2行目: 空行
# 3行目以降: 詳細な説明(必要に応じて)

# 良い例
git commit -m "Add user authentication feature"
git commit -m "Fix null pointer exception in login handler"
git commit -m "Refactor database connection logic"

# 悪い例(避けるべき)
git commit -m "update"           # 不明確
git commit -m "bug fix"          # 何のバグか不明
git commit -m "アップデート"     # 詳細不明

コミットの修正

# 最後のコミットを修正(メッセージや内容を変更)
git commit --amend

# メッセージのみを修正
git commit --amend -m "新しいメッセージ"

# ファイルを追加して直前のコミットに含める
git add forgotten-file.txt
git commit --amend --no-edit     # メッセージは変更しない

# 作成者情報を変更
git commit --amend --author="Name <email@example.com>"

空コミット

# 変更なしでコミット(CI/CDのトリガーなどに使用)
git commit --allow-empty -m "Trigger CI build"

# 空のマージコミット
git commit --allow-empty-message -m ""

その他のオプション

# 詳細な差分を表示しながらコミット
git commit -v
git commit --verbose

# コミット前にステージングエリアを確認
git commit --dry-run

# GPG署名付きコミット
git commit -S -m "署名付きコミット"
git commit --gpg-sign -m "署名付きコミット"

# コミット日時を指定
git commit --date="2026-01-01 12:00:00" -m "メッセージ"

差分の確認(git diff)

ファイルの変更内容を詳細に確認するコマンドです。 何が変更されたかを把握してからコミットすることが重要です。

基本的な使い方

# 作業ディレクトリとステージングエリアの差分
git diff

# ステージングエリアと最後のコミットの差分
git diff --staged
git diff --cached

# 作業ディレクトリと最後のコミットの差分
git diff HEAD

# 特定のファイルの差分
git diff file.txt
git diff --staged file.txt

コミット間の差分

# 2つのコミット間の差分
git diff commit1 commit2
git diff abc123 def456

# 最新のコミットと1つ前のコミット
git diff HEAD HEAD~1
git diff HEAD~1 HEAD

# ブランチ間の差分
git diff main develop
git diff main..develop    # 同じ意味

# 共通の祖先からの差分
git diff main...develop

差分の表示形式

# 統計情報のみ表示
git diff --stat

# ファイル名のみ表示
git diff --name-only

# ファイル名と変更タイプを表示
git diff --name-status

# 行ごとの変更を色分けして表示(デフォルト)
git diff --color

# 単語単位で差分を表示
git diff --word-diff

# 変更の前後n行を表示(デフォルトは3行)
git diff -U5
git diff --unified=5

外部ツールで差分表示

# 設定した外部diffツールで表示
git difftool
git difftool --staged

# 特定のツールを指定
git difftool --tool=vimdiff
git difftool --tool=vscode

その他の便利なオプション

# 空白の変更を無視
git diff -w
git diff --ignore-all-space

# 行末の空白のみ無視
git diff --ignore-space-at-eol

# バイナリファイルの差分
git diff --binary

# サブモジュールの変更も表示
git diff --submodule

# 移動・コピーの検出
git diff -M    # リネーム検出
git diff -C    # コピー検出

ファイルの削除(git rm)

Gitの追跡対象からファイルを削除します。 作業ディレクトリからも削除するか、追跡のみ解除するかを選択できます。

基本的な使い方

# ファイルを削除(作業ディレクトリとGitから両方削除)
git rm file.txt

# 複数ファイルを削除
git rm file1.txt file2.txt

# ディレクトリごと削除
git rm -r directory/

# パターンマッチで削除
git rm '*.log'
git rm 'temp/*.tmp'

追跡のみ解除

# ファイルは残して、Gitの追跡のみ解除
git rm --cached file.txt

# ディレクトリを追跡解除(ファイルは残す)
git rm -r --cached directory/

# .gitignoreに追加し忘れたファイルを削除する場合
git rm --cached secrets.env
echo "secrets.env" >> .gitignore
git add .gitignore
git commit -m "Remove secrets.env from tracking"

強制削除

# 変更があるファイルを強制削除
git rm -f file.txt
git rm --force file.txt

# ステージング済みの変更があるファイルを強制削除
git rm -f modified-file.txt

ドライラン

# 実際には削除せず、何が削除されるか確認
git rm -n file.txt
git rm --dry-run file.txt

ファイルの移動・リネーム(git mv)

ファイルを移動したりリネームしたりする場合に使用します。 履歴を保持したまま操作できます。

基本的な使い方

# ファイルをリネーム
git mv old-name.txt new-name.txt

# ファイルを移動
git mv file.txt directory/

# ファイルを移動してリネーム
git mv src/old.txt dest/new.txt

git mvの等価な操作

# 以下の3つのコマンドと等価
mv old.txt new.txt
git rm old.txt
git add new.txt

# つまり、手動で移動してもGitは自動的に検出可能
mv file.txt directory/
git add -A                 # Gitがリネームを検出

強制移動

# 移動先に同名ファイルがある場合、強制上書き
git mv -f source.txt destination.txt
git mv --force source.txt destination.txt

ドライラン

# 実際には移動せず、何が起こるか確認
git mv -n old.txt new.txt
git mv --dry-run old.txt new.txt

作業を元に戻す

誤って変更してしまった場合や、ステージングを取り消したい場合の方法です。

ステージングの取り消し

# 特定のファイルのステージングを取り消し
git restore --staged file.txt
git reset HEAD file.txt              # 古い方法

# 全ファイルのステージングを取り消し
git restore --staged .
git reset HEAD .

作業ディレクトリの変更を破棄

# 特定のファイルの変更を破棄(最後のコミット状態に戻す)
git restore file.txt
git checkout -- file.txt             # 古い方法

# 全ファイルの変更を破棄
git restore .
git checkout -- .

# 特定のコミット状態に復元
git restore --source=HEAD~1 file.txt
git restore --source=abc123 file.txt

注意事項

警告: git restoregit checkout --で変更を破棄すると、 作業ディレクトリの変更は完全に失われます。実行前に必ず確認してください。

ファイルの無視(.gitignore)

特定のファイルやディレクトリをGitの追跡対象から除外する方法です。

.gitignoreファイルの作成

# .gitignoreファイルを作成
touch .gitignore

# 基本的なパターン
# 特定のファイル
secrets.env
config.local.js

# 特定の拡張子
*.log
*.tmp
*.swp

# ディレクトリ全体
node_modules/
dist/
build/

# 特定のディレクトリ内のファイル
logs/*.log

# 例外(!で無視を解除)
*.log
!important.log

.gitignoreのパターン

# コメント行
# これはコメントです

# 空行は無視される

# ワイルドカード
*.txt          # 全てのtxtファイル
temp*          # tempで始まる全てのファイル
**/foo         # 全てのディレクトリのfoo

# ディレクトリ
dir/           # dirディレクトリとその中身全て

# 特定の場所のみ
/file.txt      # ルートディレクトリのfile.txtのみ
dir/*.txt      # dirの直下のtxtファイルのみ(サブディレクトリは除外)
dir/**/*.txt   # dirとサブディレクトリの全てのtxtファイル

既に追跡されているファイルを無視する

# 1. .gitignoreに追加
echo "file.txt" >> .gitignore

# 2. 追跡を解除(ファイルは残す)
git rm --cached file.txt

# 3. コミット
git add .gitignore
git commit -m "Stop tracking file.txt"

グローバル.gitignore

# 全リポジトリで共通して無視するファイルを設定
git config --global core.excludesfile ~/.gitignore_global

# ~/.gitignore_globalに記述
# OS固有のファイル
.DS_Store      # macOS
Thumbs.db      # Windows
*~             # Linux

# エディタ固有のファイル
.vscode/
.idea/
*.swp
*.swo

作業フローのベストプラクティス

効率的で安全な作業フローのための推奨事項です。

推奨される作業フロー

# 1. 作業開始前に状態確認
git status

# 2. 最新の変更を取得(リモートブランチがある場合)
git pull

# 3. ファイルを編集
# ... 作業 ...

# 4. 変更内容を確認
git status
git diff

# 5. 変更をステージング
git add -p                    # 部分的にステージング
# または
git add file1.txt file2.txt   # 特定ファイルをステージング

# 6. ステージング内容を確認
git diff --staged

# 7. コミット
git commit -m "適切なメッセージ"

# 8. リモートにプッシュ(必要に応じて)
git push

コミット前のチェックリスト

# ✓ git statusで状態確認
# ✓ git diffで変更内容を確認
# ✓ 意図した変更のみがステージングされているか確認
# ✓ コミットメッセージは明確か
# ✓ 1つのコミットに1つの論理的な変更が含まれているか
# ✓ デバッグ用のコードやコメントが残っていないか
# ✓ 機密情報(パスワード、APIキーなど)が含まれていないか

頻繁にコミットする

# 推奨: 小さく頻繁にコミット
git commit -m "Add user model"
git commit -m "Add user validation"
git commit -m "Add user tests"

# 非推奨: 大きな変更を1つにまとめる
git commit -m "Add user feature" # 100ファイルの変更