All Articles Claude Code

Denying Destructive Shell Commands via Hooks

Your team is excited about Claude Code. You've given it permission to run shell commands—it's faster than typing them, and it gets complex pipelines right.

Your team is excited about Claude Code. You’ve given it permission to run shell commands—it’s faster than typing them, and it gets complex pipelines right. Then someone asks it to “clean up old files” and it hands you rm -rf /usr/local/*. Your heart stops. Your hands freeze. You watch it calculate what just happened. Everything important just got deleted.

This scenario happens because the permission model alone isn’t enough. You need a second line of defense: a hook that watches what Claude is about to run and says “no” to commands that would destroy data or compromise your repository. This is essential for using Claude Code safely at scale. It’s not about not trusting Claude—it’s about catching mistakes before they become disasters.

This is where we build defense in depth. We’ll create a PreToolUse hook that detects dangerous patterns, handles command chaining and piping, provides clear feedback, supports override mechanisms, and logs attempts for security auditing. This is the intermediate-level hook pattern. It’s more complex than file protection, but it’s essential if you’re giving Claude shell access. By the end of this article, you’ll have a production-ready system that prevents catastrophic data loss while still enabling powerful automation.

Why Destructive Commands Need Special Handling

At first glance, it seems like users should just… not ask Claude Code to delete things. But the problem is more subtle. Most data loss happens through indirect deletion, not explicit requests. A developer asks Claude Code to “clean up build artifacts.” Claude Code interprets “clean up” generically and runs rm -rf build / (accidentally including root because of a parsing error). Or a developer asks to “optimize the database” and Claude runs DROP TABLE users without realizing that was actually important.

More insidiously, multi-stage commands can hide danger. A developer might innocently ask for “show me all temporary files and delete them,” and Claude Code creates a command like find /tmp -type f | xargs rm. This looks reasonable in isolation. But if the find command has an error, xargs might operate on unexpected input and delete the wrong files. Or a developer asks to “clean up old git branches” and Claude Code runs git branch | grep old | xargs git branch -D, which is exactly what was requested but catastrophically wrong if the grep pattern doesn’t work correctly.

These aren’t cases of Claude Code being malicious. They’re cases of Claude Code doing literally what was asked, without understanding the consequences. A protection hook catches these dangerous commands before they execute. It’s like having a careful ops engineer review every command Claude Code wants to run and saying “whoa, that’s dangerous, let’s talk about this first.”

The Categories of Dangerous Commands

Not all dangerous commands are obvious. Let’s categorize them:

Irreversible data deletion:
– rm -rf / path/ – Recursive deletion with force flag
– find ... -delete – Find-based deletion
– dd if=/dev/zero of=/dev/sdX – Destructive write to block device
– mkfs.* – Format filesystem commands
– shred, wipe – Secure deletion that can’t be recovered

Database destruction:
– DROP TABLE – Delete entire table
– DROP DATABASE – Delete entire database
– TRUNCATE – Irreversibly delete all rows
– ALTER TABLE ... MODIFY ... NOT NULL on existing data – Can corrupt data

Version control sabotage:
– git push --force – Force push that can lose commit history
– git reset --hard – Irreversibly discard uncommitted changes
– git branch -D – Delete branch without safety checks
– git filter-branch – Rewrite history (can break in repos with history)

System compromise:
– Commands running as root that modify critical system files
– sudo rm -rf patterns
– Modification of authentication files, firewall rules, etc.

Credential exposure:
– env | grep PASSWORD piped to output
– cat ~/.aws/credentials piped to stdout
– Echoing secrets to log files

Not all of these are equally dangerous in all contexts. In a local dev environment, git push --force might be acceptable (though risky). In a shared production system, it’s catastrophic. Your hook should understand context and be configurable.

Building Your First Defense Hook: Pattern Matching

The foundation of defense is pattern matching. Before Claude Code executes a shell command, your hook examines it and checks for dangerous patterns:

// .claude/hooks/pre-tool-use/deny-destructive-commands.mjs

const DANGEROUS_PATTERNS = [
  // Recursive deletion
  /rm\s+-[a-zA-Z]*r[a-zA-Z]*f?\s+/,
  /rm\s+-[a-zA-Z]*f[a-zA-Z]*r?\s+/,

  // Force deletion variants
  /rm\s+-f\s+/,
  /find\s+.*\s+-delete/,

  // Database destruction
  /DROP\s+(TABLE|DATABASE)\s+/i,
  /TRUNCATE\s+TABLE/i,

  // Destructive git
  /git\s+push\s+--force/,
  /git\s+reset\s+--hard/,
  /git\s+branch\s+-D\s+/,

  // Filesystem formats
  /mkfs\./,
  /dd\s+if=\/dev\/zero/,
];

export const handler = async (context) => {
  const { toolName, toolInput } = context;

  // Only intercept shell commands
  if (toolName !== "bash" && toolName !== "shell") {
    return { allowed: true };
  }

  const command = toolInput.command || toolInput;

  // Check each pattern
  for (const pattern of DANGEROUS_PATTERNS) {
    if (pattern.test(command)) {
      return {
        allowed: false,
        reason: "Destructive command detected",
        pattern: pattern.toString(),
        command,
        suggestion: "This command may cause data loss. Please review carefully.",
        override_token: null
      };
    }
  }

  return { allowed: true };
};

This hook blocks commands matching dangerous patterns. It’s simple, fast, and catches obvious dangers.

But this basic approach has problems. What if someone legitimately wants to delete files? What if the context matters? What if there are false positives?

Improving Detection: Understanding Context and Scope

Pattern matching alone isn’t enough. Some commands are dangerous everywhere. Others are dangerous only in certain contexts.

// Enhanced hook with context awareness

const ALWAYS_DANGEROUS = [
  /git\s+push\s+--force/,  // Never safe to force push
  /DROP\s+DATABASE/i,       // Destroying entire databases is never ok
];

const CONTEXT_DANGEROUS = [
  {
    pattern: /rm\s+-r/,
    dangerous_when: (context) => {
      // Only dangerous if target is system path or root
      return context.target_path?.startsWith("/") &&
             !context.target_path?.startsWith("/tmp") &&
             !context.target_path?.startsWith("/home");
    }
  },
  {
    pattern: /DROP\s+TABLE/i,
    dangerous_when: (context) => {
      // Only dangerous if not in development environment
      return context.environment !== "development";
    }
  },
  {
    pattern: /git\s+reset\s+--hard/,
    dangerous_when: (context) => {
      // Only dangerous if there are uncommitted changes
      return context.has_uncommitted_changes;
    }
  }
];

export const handler = async (context) => {
  const { toolName, toolInput } = context;

  if (toolName !== "bash" && toolName !== "shell") {
    return { allowed: true };
  }

  const command = toolInput.command || toolInput;

  // Check always-dangerous patterns
  for (const pattern of ALWAYS_DANGEROUS) {
    if (pattern.test(command)) {
      return {
        allowed: false,
        severity: "critical",
        reason: "This command is always dangerous",
        command
      };
    }
  }

  // Check context-dependent patterns
  for (const check of CONTEXT_DANGEROUS) {
    if (check.pattern.test(command) && check.dangerous_when(context)) {
      return {
        allowed: false,
        severity: "high",
        reason: "This command is dangerous in this context",
        context: context.environment,
        command
      };
    }
  }

  return { allowed: true };
};

Context awareness lets you be smart about what’s dangerous. rm -rf /tmp/build-artifacts is reasonable. rm -rf /home is not.

Handling Command Chaining and Piping

Danger hides in pipelines. A developer asks to “find and delete orphaned branches” and Claude Code produces: git branch | grep -v main | xargs git branch -D. This chains multiple commands, and each introduces risk.

Pipelines need special handling because they compose multiple commands:

// Analyzing piped commands

function analyzeCommand(command) {
  // Split by pipe to get individual commands
  const parts = command.split('|').map(s => s.trim());

  // Check each part for dangers
  const dangers = [];

  for (let i = 0; i < parts.length; i++) {
    const part = parts[i];

    // Check if it's destructive
    if (containsDangerous(part)) {
      dangers.push({
        position: i,
        command: part,
        reason: "Destructive command in pipeline"
      });
    }
  }

  // Special case: xargs with deletion
  if (command.includes('xargs') &&
      /xargs\s+(rm|git\s+branch\s+-D)/.test(command)) {
    dangers.push({
      pattern: "xargs deletion",
      reason: "Piped deletion through xargs risks deleting wrong files if piped input has errors"
    });
  }

  // Special case: find with deletion
  if (/find\s+.*\s+\|\s+xargs\s+rm/.test(command)) {
    dangers.push({
      pattern: "find piped to xargs rm",
      reason: "If find fails or has unexpected output, xargs might delete wrong files"
    });
  }

  return dangers;
}

function containsDangerous(commandPart) {
  return /rm\s+-[rf]|DROP\s+TABLE|git\s+push\s+--force/.test(commandPart);
}

Pipeline analysis catches the subtle dangers that simple pattern matching misses. By analyzing each component and understanding how they compose, you can catch mistakes.

Override Mechanisms: Allowing Necessary Actions

Sometimes you legitimately need to do dangerous things. A developer needs to delete a large directory. Another needs to drop a test database. Your hook should allow this, but safely.

A good override mechanism requires:

  1. Explicit request: The human must explicitly say “I know this is dangerous and I want to do it anyway”
  2. Audit trail: Log who requested the override, when, and what command they ran
  3. Verification: Show the human exactly what will run
  4. Limits: Override should be time-limited or session-limited, not permanent
// Override mechanism

const OVERRIDE_TOKEN_LIFETIME = 5 * 60 * 1000; // 5 minutes
const overrideTokens = new Map();

export const handler = async (context) => {
  const { toolName, toolInput } = context;

  if (toolName !== "bash") {
    return { allowed: true };
  }

  const command = toolInput.command || toolInput;
  const overrideToken = toolInput.override_token;

  // Check if this is a dangerous command
  const danger = checkForDanger(command);

  if (!danger) {
    return { allowed: true };
  }

  // Check if override token is valid
  if (overrideToken && isValidOverride(overrideToken, command)) {
    // Log the override
    console.log(JSON.stringify({
      timestamp: new Date().toISOString(),
      type: "destructive_command_override",
      command,
      override_token: overrideToken,
      user: context.user
    }));

    // Use the override (one-time use)
    overrideTokens.delete(overrideToken);
    return { allowed: true };
  }

  // Deny and provide override instructions
  const newToken = generateOverrideToken(command);
  overrideTokens.set(newToken, {
    command,
    created_at: Date.now(),
    expires_at: Date.now() + OVERRIDE_TOKEN_LIFETIME
  });

  return {
    allowed: false,
    danger_reason: danger.reason,
    command,
    override_instructions: `
This command was blocked because it may cause data loss.

COMMAND: ${command}
REASON: ${danger.reason}

If you understand the risks and want to proceed:
1. Verify this is exactly the command you want to run
2. Re-run with: \`/override --token ${newToken}\`

The override token expires in 5 minutes.
Overrides are logged for audit purposes.
    `
  };
};

function isValidOverride(token, command) {
  const override = overrideTokens.get(token);
  if (!override) return false;

  // Token must not be expired
  if (Date.now() > override.expires_at) {
    overrideTokens.delete(token);
    return false;
  }

  // Token must be for this exact command
  if (override.command !== command) return false;

  return true;
}

function generateOverrideToken(command) {
  // Generate a cryptographically random token
  const buffer = new Uint8Array(32);
  crypto.getRandomValues(buffer);
  return Array.from(buffer).map(b => b.toString(16).padStart(2, '0')).join('');
}

Override tokens are time-limited, command-specific, and one-time use. This prevents accidental data loss while allowing legitimate necessary actions. The audit log records who used overrides and when, creating accountability.

Logging and Audit Trails

Every blocked command should be logged. Every override should be logged. This creates visibility into what Claude Code is trying to do.

// Comprehensive logging

function logDangerousCommandAttempt(context) {
  const logEntry = {
    timestamp: new Date().toISOString(),
    type: "dangerous_command_blocked",
    user: context.user,
    session_id: context.session_id,
    command: context.command,
    danger_category: context.danger_category,
    environment: context.environment,
    ip_address: context.ip_address,
    action_taken: "blocked"
  };

  // Write to local audit log
  const auditLog = join(process.env.HOME, ".claude", "audit", "destructive-commands.jsonl");
  appendToLog(auditLog, logEntry);

  // Alert if severity is critical
  if (context.severity === "critical") {
    sendAlert(`Critical destructive command blocked: ${context.command}`);
  }
}

function appendToLog(path, entry) {
  const line = JSON.stringify(entry) + "\n";
  appendFileSync(path, line);
}

Audit logs answer important questions:
– What dangerous commands has Claude Code tried to run?
– Which developers have requested overrides?
– What pattern of attempts precedes a successful attack?
– Are there repeated patterns suggesting misunderstanding?

Over time, audit logs reveal what dangerous patterns need to be blocked globally versus what’s environment-specific.

Building a Whitelist for Trusted Commands

Not every potentially dangerous command is actually dangerous in context. Some developers legitimately need to delete large directories. Some teams delete old git branches regularly.

A whitelist mechanism lets you approve specific commands while still blocking unknown dangerous patterns:

// Whitelist system

const WHITELISTED_COMMANDS = [
  {
    pattern: /rm\s+-rf\s+\/tmp\/build-artifacts/,
    reason: "Clean build artifacts from CI",
    approved_by: "devops-team",
    approval_date: "2026-03-01",
    last_used: "2026-03-15"
  },
  {
    pattern: /git\s+push\s+--force.*experimental/,
    reason: "Force push to experimental branch only",
    approved_by: "eng-lead",
    condition: (cmd) => cmd.includes("experimental"),
    last_used: "2026-03-14"
  }
];

export const handler = async (context) => {
  const command = context.toolInput.command;

  // Check whitelist first
  for (const entry of WHITELISTED_COMMANDS) {
    if (entry.pattern.test(command)) {
      if (entry.condition && !entry.condition(command)) {
        continue; // Condition not met, check next
      }

      // Log whitelist usage
      console.log({
        type: "whitelisted_dangerous_command",
        command,
        timestamp: new Date().toISOString()
      });

      return { allowed: true };
    }
  }

  // Not whitelisted, check if it's dangerous
  const danger = checkForDanger(command);
  if (danger) {
    return {
      allowed: false,
      danger_reason: danger.reason
    };
  }

  return { allowed: true };
};

Whitelisting lets you gradually expand what’s allowed as you gain confidence. You start very restrictive (block everything dangerous), then whitelist specific safe patterns that you’ve vetted.

Real-World Scenarios: Where This Hook Prevents Disasters

Understanding these patterns theoretically is useful. Seeing them prevent actual disasters is compelling.

Scenario 1: The Accidental rm -rf /

A developer asked Claude Code to “remove all compiled Python files to clean up the repo.” Claude Code interpreted this as needing to remove all .pyc files and generated: find . -name '*.pyc' -delete but made a typo and actually ran find / -name '*.pyc' -delete (note the / instead of ./).

The hook caught find / -name '*.pyc' -delete and blocked it. The developer was confused at first, then realized the mistake. They re-requested with a more specific path: find ./src -name '*.pyc' -delete. The hook allowed this because it was scoped to a specific directory, not the root. The developer learned to be more specific. No data loss.

Without the hook, the system would have spent the next hour deleting every .pyc file from root downward, corrupting Python installations system-wide and causing massive problems.

Scenario 2: The Force Push That Almost Happened

A developer asked Claude Code to “push this feature branch to update the pull request.” Claude Code generated git push -u origin feature/new-feature, which is correct. But then in a follow-up request, the developer said “I’ve made final edits, force push these changes.” Claude Code interpreted this as needing to force push the already-pushed commits and generated git push --force origin feature/new-feature.

The hook blocked the force push. The developer had to manually verify they actually wanted to force push. They realized they didn’t—they just wanted a normal push. The hook saved them from overwriting collaborators’ commits on a shared branch.

Scenario 3: The DROP TABLE That Never Happened

A backend engineer was working on database migrations and asked Claude Code to “clean up the old event_log table now that we’ve migrated to the new events table.” Claude Code generated: DROP TABLE event_log;

The hook blocked it and asked for an override. The engineer provided an override token. Then, before running the command, they realized they should check if there were any references to event_log in the codebase first. They skipped the override and searched for references. They found three codebase locations still using event_log. They updated those first, then dropped the table.

Without the forced verification step, the drop would have succeeded immediately, breaking the application. The override mechanism bought time for the engineer to think and verify.

Advanced: Machine Learning Pattern Detection

For teams with sophisticated security needs, pattern matching can be enhanced with ML-based anomaly detection. As you log command attempts, patterns emerge. ML can learn what’s normal for your team and what’s suspicious:

// ML-enhanced detection (conceptual)

async function detectAnomaly(command, context) {
  const features = extractFeatures(command, context);
  // Features: command_length, file_operations, network_ops, user_history, time_of_day, etc.

  const prediction = await mlModel.predict(features);

  if (prediction.anomaly_score > 0.8) {
    return {
      anomalous: true,
      reason: `Unusual command pattern (${prediction.anomaly_reason})`,
      confidence: prediction.anomaly_score
    };
  }

  return { anomalous: false };
}

This allows catching truly novel attack patterns that don’t match known signatures.

Measuring Hook Effectiveness

Track metrics to understand if your hook is working:

  • Commands blocked: How many dangerous commands did the hook stop?
  • Override requests: How many times did developers request overrides? (High number might indicate false positives)
  • Audit log patterns: Are there patterns in what gets blocked? (Might indicate misunderstandings about what’s dangerous)
  • Actual incidents prevented: When a developer would have run something dangerous without the hook, the hook caught it

Over time, these metrics justify the investment in defensive infrastructure. A single prevented data loss incident—which could cost thousands of dollars in recovery time and lost productivity—pays for months of development and maintenance of your defensive hooks.

Implementing Hooks in Team Workflows

Implementing destructive command protection hooks requires cultural buy-in alongside technical implementation. Developers need to understand why the protection exists and that it’s helping them, not hindering them.

First, educate: Show your team real examples of dangerous commands that could be run accidentally. “Someone could ask Claude Code to clean up build artifacts and accidentally wipe production configs.” This makes the risk concrete.

Second, implement gradually: Start with the most obviously dangerous patterns—rm -rf /, DROP DATABASE, git push --force. Prove value before expanding. Over time, add more nuanced detection.

Third, gather feedback: When the hook blocks commands, ask: “Was this a false positive?” If a command is getting blocked repeatedly despite being safe, adjust the hook. You want high signal-to-noise ratio so developers trust the hook.

Fourth, document overrides: When someone uses an override token, make sure it’s well-documented why. Over time, patterns of overrides indicate legitimate use cases that should be whitelisted.

Fifth, share learnings: When the hook catches something dangerous, share it with the team. “The hook caught this dangerous command today—good thing it was there.” Celebrates the hook’s value and trains people’s instincts about danger.

Threat Models and Defense Levels

Different organizations have different threat models. What’s appropriate for a small startup might be overkill for an enterprise with dedicated security teams, or insufficient for a team managing critical infrastructure.

Low defense: Basic pattern matching for obviously dangerous commands (rm -rf /, DROP DATABASE). Good for small teams where everyone knows each other and accidentally running something dangerous is the only realistic risk.

Medium defense: Pattern matching plus context awareness. Different rules for development vs. production. Whitelisting for approved patterns. Useful for mid-size teams where there’s some separation between dev and prod environments.

High defense: Machine learning anomaly detection plus comprehensive audit logging plus mandatory overrides for all dangerous operations. Useful for teams managing critical infrastructure where the risk of data loss is severe.

Enterprise defense: All of the above plus integration with identity and access management, comprehensive SIEM logging, alert integration with security operations centers, and regular penetration testing of the hook system itself.

Choose a defense level that matches your risk tolerance. Implement it well. Review periodically and upgrade if your risk profile changes.

Integration with CI/CD and Deployment Pipelines

The most powerful use of destructive command hooks is preventing dangerous operations in automated deployment pipelines. A human might make a mistake with a destructive command. An automated system making the same mistake could cause infrastructure-wide damage before anyone notices.

Integrate your hooks into deployment pipelines so that every command Claude Code wants to run in an automated context goes through the same protective review:

# CI/CD pipeline example
pipeline:
  build:
    script: ./build.sh
    hooks:
      pre_script: check-destructive-commands

  deploy:
    script: ./deploy.sh
    hooks:
      pre_script: check-destructive-commands
      require_override_for: ["rm", "DROP", "git push --force"]

  cleanup:
    script: ./cleanup.sh
    hooks:
      pre_script: check-destructive-commands
      deny_without_approval: true

When deployment pipelines use Claude Code for automation, the same protective measures apply. This prevents mistakes that could take your entire system offline.

Building Organizational Context and Culture

The technical aspects of protective hooks are important. But equally important is building a culture where safety is valued and where developers understand why these protections exist.

Teams that successfully implement destructive command protection do a few things consistently:

They celebrate near-misses: When the hook catches something that could have been catastrophic, they acknowledge it. “The hook caught a dangerous command today. Without it, we would have lost two hours of data recovery.” This reinforces that the hook is valuable.

They invest in education: New team members learn about the hook during onboarding. They understand what’s dangerous and why. They see examples of what happens when dangerous commands run without protection.

They adjust for false positives: If the hook is blocking legitimate commands, they work with the team to refine the rules. They don’t force developers to fight the hook—they fix the hook to be smarter.

They own their data: There’s a cultural understanding that data safety is everyone’s responsibility. Developers don’t just avoid destructive commands—they actively think about how to prevent mistakes, including using these protective hooks as a safety net.

They build trust gradually: Initially, developers might resent the protection. Over time, as they see it preventing mistakes, they come to appreciate it. By the time it matters—when a dangerous command is about to run—developers trust that the hook is protecting them, not hindering them.

Future Directions: Advanced Safety Mechanisms

As Claude Code capabilities expand, so do the risks. Future safety mechanisms might include:

Semantic analysis: Instead of pattern matching, analyze the actual intent of the command. “I want to delete temporary build files” is different from “I want to delete everything in /home/.” Understanding intent is harder but more accurate.

Safe operation suggestions: When a dangerous command is blocked, suggest safe alternatives. “Instead of rm -rf, you could use find /path -name pattern -delete with a specific path.” This helps developers accomplish their goals safely.

Rollback capabilities: For certain operations, build in automatic rollback. If deletion operations cause problems, automatically restore from backup. This reduces the severity of mistakes.

Transactional commands: Treat command execution like database transactions. Commands can be grouped, and the entire group rolls back if any part fails or has unexpected consequences.

These future mechanisms will make systems even safer, especially as Claude Code takes on more critical infrastructure tasks.

Conclusion: Defense in Depth for Production Systems

Destructive command protection hooks represent one layer of defense in depth. They’re not a substitute for good backups, careful testing, or strong access controls. But they’re an essential layer that catches mistakes before they cause damage.

Implement them thoughtfully. Start with obvious patterns. Build context awareness. Gather feedback. Expand gradually. Measure impact. And most importantly, build a culture where safety is valued and where everyone understands that protective mechanisms help, rather than hinder, productive work.

The cost of prevention is tiny compared to the cost of recovery. A few hours building protective hooks and a few seconds of overhead per command prevent incidents that cost days of recovery work. That’s an investment worth making.


-iNet

Defense in depth saves companies money. Implement it early.

Free Discovery Call

Start With a Conversation, Not a Commitment

Every engagement begins with a free 30-minute discovery call. We'll map what's slowing your business down and tell you exactly what we'd fix first – no pitch deck, no obligation.