Claude Code hooks設定ガイド

Claude Codeの特定イベントで自動実行するスクリプトの設定方法。


hooksとは

Claude Codeの動作にフックして自動処理を実行する仕組み。

  • ファイル保存時に自動フォーマット
  • コミット前に自動テスト
  • セッション開始時に環境確認

手順

01. 設定ファイル作成

mkdir -p .claude
touch .claude/settings.json

02. hooks設定を記述

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write",
        "hooks": [
          {
            "type": "command",
            "command": "echo 'ファイル書き込み前'"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Write",
        "hooks": [
          {
            "type": "command",
            "command": "prettier --write $CLAUDE_FILE_PATH"
          }
        ]
      }
    ]
  }
}

03. Claude Code再起動

claude

04. 完了


参考リンク


ここから先は、各hookの詳細と実用例を解説します。


Q&A - hook種類

利用可能なhook

| Hook名 | タイミング | |--------|-----------| | PreToolUse | ツール実行前 | | PostToolUse | ツール実行後 | | Notification | 通知時 | | Stop | 停止時 |

マッチャー

ツール名でフィルタリング:

  • Write - ファイル書き込み
  • Edit - ファイル編集
  • Bash - コマンド実行
  • Read - ファイル読み込み

Q&A - 実用例

ファイル保存時に自動フォーマット

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "prettier --write $CLAUDE_FILE_PATH 2>/dev/null || true"
          }
        ]
      }
    ]
  }
}

Python保存時に型チェック

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write",
        "hooks": [
          {
            "type": "command",
            "command": "if [[ $CLAUDE_FILE_PATH == *.py ]]; then mypy $CLAUDE_FILE_PATH; fi"
          }
        ]
      }
    ]
  }
}

危険なコマンドをブロック

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "if echo '$CLAUDE_TOOL_INPUT' | grep -q 'rm -rf'; then exit 1; fi"
          }
        ]
      }
    ]
  }
}

Q&A - 環境変数

hookで使える変数

| 変数 | 内容 | |------|------| | $CLAUDE_FILE_PATH | 対象ファイルパス | | $CLAUDE_TOOL_INPUT | ツールへの入力 | | $CLAUDE_TOOL_OUTPUT | ツールからの出力 |


Q&A - トラブル

hookが動かない

1. JSON構文エラーがないか確認 2. コマンドのパスが正しいか確認 3. 実行権限があるか確認

hookでエラーが出る

|| true を追加してエラーを無視:
{
  "command": "prettier --write $CLAUDE_FILE_PATH || true"
}

特定ファイルのみ対象

シェルで条件分岐:

{
  "command": "if [[ $CLAUDE_FILE_PATH == *.js ]]; then eslint $CLAUDE_FILE_PATH; fi"
}

Q&A - 高度な設定

複数hookの連鎖

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write",
        "hooks": [
          {"type": "command", "command": "prettier --write $CLAUDE_FILE_PATH"},
          {"type": "command", "command": "eslint $CLAUDE_FILE_PATH"}
        ]
      }
    ]
  }
}

外部スクリプト呼び出し

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write",
        "hooks": [
          {"type": "command", "command": "./.claude/scripts/post-write.sh $CLAUDE_FILE_PATH"}
        ]
      }
    ]
  }
}

タグ: #ClaudeCode #hooks #自動化 #開発効率化 #スクリプト
← Claude Codeシリーズ一覧へ