一行要約
claude -p は Agent SDK の CLI 版であり、CI やスクリプトで再現性が要るなら --bare(hook / skill / plugin / MCP / auto memory / CLAUDE.md の自動発見をすべて飛ばす)を付けるのが推奨。
要点
基本
claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"- 成功で exit code 0、失敗で非ゼロ。スクリプトは exit status で分岐できる
- 不正なフラグは実行前に stderr へ報告される。実行中の失敗(認証エラーなど)は stdout に結果として出る
-pと併用できないオプションがある —--bgは拒否される。--cloudはタスク記述と併用すると拒否され、セッション ID と併用するとそのクラウドセッションにメッセージを積んで終了する
--bare(CI での推奨)
Add
--bareto reduce startup time by skipping auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md.--bareを付けると、hook・skill・plugin・MCP サーバ・auto memory・CLAUDE.md の自動探索を省略して起動時間を短縮できる。
A hook in a teammate’s
~/.claudeor an MCP server in the project’s.mcp.jsonwon’t run, because bare mode never reads them. teammate の~/.claudeにある hook や、プロジェクトの.mcp.jsonにある MCP サーバは動かない。bare モードはそれらを一切読まないからである。
認証の注意: bare mode は OAuth 認証情報も system keychain も読まない。Anthropic API を使うなら ANTHROPIC_API_KEY を環境に設定する(Bedrock / Agent Platform / Foundry は各プロバイダの認証情報を通常どおり読む)。
bare mode で使えるツールは Bash、ファイル読み取り、ファイル編集。必要な context はフラグで渡す。
| ロードしたいもの | フラグ |
|---|---|
| system prompt への追記 | --append-system-prompt, --append-system-prompt-file |
| 設定 | --settings <file-or-json> |
| MCP サーバ | --mcp-config <file-or-json> |
| カスタムエージェント | --agents <json> |
| plugin | --plugin-dir <path>, --plugin-url <url> |
出力形式
--output-format | 内容 |
|---|---|
text(既定) | プレーンテキスト |
json | 結果・セッション ID・メタデータを含む構造化 JSON。total_cost_usd とモデル別のコスト内訳も含む(クライアント側の推定値) |
stream-json | 改行区切り JSON。リアルタイムストリーミング |
スキーマに従わせるには --output-format json + --json-schema。結果は structured_output フィールドに入る。
Claude Code accepts schemas that use the
formatkeyword, such as"format": "email", but treatsformatas an annotation and doesn’t enforce it. Claude Code は"format": "email"のようにformatキーワードを使うスキーマを受け付けるが、formatは注釈として扱い、強制はしない。
ストリーミング
--output-format stream-json --verbose --include-partial-messages でトークンごとに受け取る。最後の行は result メッセージで、最終応答テキスト・コスト・セッションメタデータを含む。
subagent のメッセージは parent_tool_use_id にそれを起こしたツール呼び出しの ID を持つ(メイン会話は null)。既定では subagent の tool_use / tool_result ブロックだけが出る。 --forward-subagent-text または CLAUDE_CODE_FORWARD_SUBAGENT_TEXT でテキストと thinking も出せる。入れ子の subagent も全深さで転送されるので、ID を辿れば入れ子ツリーを再構築できる。
主要なイベント:
| イベント | 用途 |
|---|---|
system/init | セッションメタデータ(モデル、ツール、MCP サーバ、plugin)。通常は最初のイベント |
system/api_retry | リトライ可能なエラーでの再試行。attempt / max_retries / retry_delay_ms / error_status / error |
system/plugin_install | marketplace plugin のインストール進捗(CLAUDE_CODE_SYNC_PLUGIN_INSTALL 設定時) |
CI で plugin / MCP のロード失敗を検知する(system/init のフィールド):
| フィールド | 内容 |
|---|---|
plugins | ロードに成功した plugin |
plugin_errors | ロード時エラー。エラーがなければキー自体が省略される |
mcp_servers | セッション内の MCP サーバと status |
mcp_server_errors | 検証で skip された --mcp-config エントリ。エラーがなければキーが省略されるので、非空配列で CI を落とせる |
system/initのcapabilities配列を見ればプロトコル挙動を feature-detect できる。バージョン文字列の比較ではなくこちらを使う。
権限の扱い
--allowedToolsで個別ツールを事前承認する- セッション全体の基準を決めるなら permission mode を渡す
dontAsk—permissions.allowと読み取り専用コマンド以外を拒否。ロックダウンした CI 向けacceptEdits— ファイル書き込みとmkdir/touch/mv/cpを自動承認。それ以外のシェルコマンドとネットワークリクエストには--allowedToolsか allow ルールが要る。なければ実行しようとした時点で run が中断する
The
--allowedToolsflag uses permission rule syntax. The trailing*enables prefix matching, soBash(git diff *)allows any command starting withgit diff. The space before*is important: without it,Bash(git diff*)would also matchgit diff-index.--allowedToolsフラグは permission ルールの構文を使う。末尾の*が前方一致を有効にするので、Bash(git diff *)はgit diffで始まる任意のコマンドを許可する。*の前の空白が重要である。空白がないとBash(git diff*)はgit diff-indexにも一致してしまう。
バックグラウンドタスクの扱い
- バックグラウンド Bash タスク(dev server や watch build)は、最終結果が返り stdin が閉じてから約5秒後に終了させられる
- バックグラウンドの subagent と workflow はこの5秒の対象外 — 結果が最終出力の一部なので
claude -pは完了を待つ。待ち時間は既定で最大10分(CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MSで調整、0で無制限) - SIGTERM で停止すると、進行中のターンを中断し、実行中の Bash のプロセスツリーを終了させ、
SessionEndhook を走らせて exit code 143 で終了する
その他の注意
- パイプで渡す stdin は 10MB が上限。 超えるとエラーで非ゼロ終了する。大きい入力はファイルに書いてパスをプロンプトで参照する
-pモードでも user-invocable な skill とカスタムコマンドは使える — プロンプト文字列に/skill-nameを入れれば展開される。/loginのような端末専用の組み込みコマンドは使えない/model、/effort、/fast、/color、/renameは値を引数として受け取る(/model sonnet)。設定変更は/config thinking=falseの形
そのまま使える具体例
CI 向けの最小形:
claude --bare -p "Summarize README.md" --allowedTools "Read"パイプで渡してファイルに書き出す:
cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txtpackage.json に typo linter として組み込む(diff をパイプするので Bash 権限が不要になるのが巧い):
{
"scripts": {
"lint:claude": "git diff main | claude -p \"you are a typo linter. for each typo in this diff, report filename:line on one line and the issue on the next. return nothing else.\""
}
}構造化出力:
claude -p "Extract the main function names from auth.py" \
--output-format json \
--json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}'jq で取り出す:
claude -p "Summarize this project" --output-format json | jq -r '.result'
claude -p "Extract function names from auth.py" \
--output-format json \
--json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \
| jq '.structured_output'ストリーミングしてテキストだけ流す:
claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \
jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'ツールを事前承認する:
claude -p "Run the test suite and fix any failures" \
--allowedTools "Bash,Read,Edit"
claude -p "Apply the lint fixes" --permission-mode acceptEditsコミットを作らせる(接頭辞マッチの空白に注意):
claude -p "Look at my staged changes and create an appropriate commit" \
--allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)"PR のセキュリティレビュースクリプト(review.sh、bash review.sh 123 で実行):
gh pr diff "$1" | claude -p \
--append-system-prompt "You are a security engineer. Review for vulnerabilities." \
--output-format json会話を継続する:
# First request
claude -p "Review this codebase for performance issues"
# Continue the most recent conversation
claude -p "Now focus on the database queries" --continue
# 特定のセッションを resume する
session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
claude -p "Continue that review" --resume "$session_id"原典で言及されている関連文書
- permission-modes —
dontAsk/acceptEditsの詳細 - sub-agents — バックグラウンド subagent の待機とツールセット
- hooks-guide —
-pモードで走る hook(--bareでは走らない) - workflows —
-pでは workflow が待機実行になる - costs —
--output-format jsonのtotal_cost_usd