Back to snippets
Tip

Claude Code Hooks for DevOps Workflows

2 min read
claude-codeaiautomationdevopsproductivity

Automate pre and post-execution tasks in Claude Code using hooks for linting, formatting, and validation.

Claude Code hooks let you run custom scripts before or after Claude executes tools. Configure them in ~/.claude/settings.json (user) or .claude/settings.json (project).

~/.claude/settings.json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "npx prettier --write \"$(jq -r '.tool_input.file_path')\""
          }
        ]
      }
    ],
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.command' >> ~/.claude/bash-log.txt"
          }
        ]
      }
    ]
  }
}
bash

Available Hook Events

  • PreToolUse - Before tool execution (can modify input, allow/deny)
  • PostToolUse - After successful tool execution
  • PostToolUseFailure - When a tool fails
  • PermissionRequest - When permission dialog is shown
  • UserPromptSubmit - When user submits a prompt (can inject context)
  • Stop / SubagentStop - When agent finishes (can force continuation)
  • SessionStart / SessionEnd - Session lifecycle (inject startup context)
  • SubagentStart - When spawning a subagent
  • Setup - During --init or --maintenance (repo initialization)
  • PreCompact - Before context compaction (manual or auto)
  • Notification - When notifications are sent

Hook Decision Control

Hooks can output JSON to control behavior. Exit code 0 with JSON stdout enables advanced control:

  • PreToolUse: { "permissionDecision": "allow|deny|ask", "updatedInput": {...} }
  • PostToolUse: { "decision": "block", "additionalContext": "..." }
  • UserPromptSubmit: { "decision": "block", "reason": "..." }
  • Stop: { "decision": "block", "reason": "keep working on X" }
View active hooks
Use the /hooks command in Claude Code to view and manage hooks interactively. Hooks receive JSON via stdin with session_id, tool_name, tool_input, cwd, and permission_mode.
By Brandon StokesWritten byClaude