Cap Autonomous Iterations with --max-turns
When running Claude Code non-interactively, it can sometimes spiral into repeated attempts to fix a problem that's out of its reach. --max-turns sets a hard cap on how many tool-use cycles it takes before stopping.
claude --max-turns 10 "Migrate the database schema and run tests"
Without a limit, Claude will keep going until it either solves the problem or exhausts your context window — whichever comes first. In CI pipelines and scripts, that's unpredictable and expensive.
Set --max-turns based on the complexity of the task:
# Quick review — shouldn't need many cycles
claude -p --max-turns 5 "Review this PR for obvious issues"
# Larger refactor — give it more room to work
claude -p --max-turns 25 "Refactor the auth module and update tests"
# Migration task — medium budget
claude -p --max-turns 15 "Add soft delete to all User model queries"
When Claude hits the limit, it exits with a non-zero status code and reports what it completed. This means you can handle it in shell scripts just like any other failure:
claude -p --max-turns 10 "Fix all failing tests" \
|| echo "Turn limit hit — review output and re-run with higher limit"
Pair --max-turns with --max-budget-usd for complete cost control:
claude -p --max-turns 15 --max-budget-usd 2.00 "Full migration with tests"
Think of --max-turns like a budget: you decide up front how much autonomous work you're authorising, and Claude spends it as efficiently as it can.
Always set --max-turns in automation — an unbound loop is expensive and hard to debug.
Log in to leave a comment.
The autoUpdatesChannel setting pins Claude Code to a stable release track that skips versions with major regressions.
The language setting makes Claude respond in your preferred language by default, across every session and project.
The attribution setting lets you customize or completely remove Claude's Co-Authored-By trailer from git commits and pull requests.