CLI 參考指南 (CLI Reference)
總覽 (Overview)
Claude Code CLI (命令行介面 / Command Line Interface) 是與 Claude Code 互動的主要方式。它提供了強大的選項來執行查詢 (Queries)、管理工作階段 (Sessions)、設定模型 (Models),以及將 Claude 整合到您的開發工作流程 (Development Workflows) 中。
架構 (Architecture)
graph TD
A["使用者終端機 (User Terminal)"] -->|"claude [options] [query]"| B["Claude Code CLI"]
B -->|互動式 (Interactive)| C["REPL 模式 (REPL Mode)"]
B -->|"--print"| D["列印模式 (Print Mode / SDK)"]
B -->|"--resume"| E["恢復工作階段 (Session Resume)"]
C -->|對話 (Conversation)| F["Claude API"]
D -->|單一查詢 (Single Query)| F
E -->|載入脈絡 (Load Context)| F
F -->|回應 (Response)| G["輸出 (Output)"]
G -->|text/json/stream-json| H["終端機/管道 (Terminal/Pipe)"]執行階段與封裝 (Runtime & Packaging)
自 v2.1.113 起,Claude Code CLI 會透過可選的 npm 依賴套件啟動跨平台的原生二進位檔 (Native Per-Platform Binary)(macOS、Linux、Windows)。在安裝時,二進位檔會自動與您的作業系統 (OS) 和架構比對 — 舊版的打包 JavaScript 執行階段 (Bundled-JavaScript Runtime) 在 macOS 或 Linux 上已不再是預設選項。
使用者端的安裝方式保持不變:npm install -g @anthropic-ai/claude-code 仍然有效且依然是推薦的做法。在幕後,npm 會為您的平台抓取正確的原生二進位檔。
下載主機 (Download host) (v2.1.116+):原生二進位檔構件從 https://downloads.claude.ai/claude-code-releases 提供服務。
企業 / 代理伺服器使用者 (Corporate / proxy users):如果您的網路需要明確的白名單 (Allowlist),請將
downloads.claude.ai(以及https://downloads.claude.ai/claude-code-releases)新增至您的代理出口規則中。先前僅將storage.googleapis.com或 npm registry 列入白名單的環境將需要更新,否則claude update與初始安裝將會失敗。
舊版的 JavaScript 打包檔仍會為 Windows 以及固定 (Pinned) 使用該檔的環境生成;這些安裝繼續將 Glob 和 Grep 作為一等工具 (First-Class Tools) 提供(參見 工具與權限管理 下的 Glob/Grep 腳註)。
CLI 指令 (CLI Commands)
| 指令 (Command) | 說明 (Description) | 範例 (Example) |
|---|---|---|
claude | 啟動互動式 REPL | claude |
claude "query" | 使用初始提示詞 (Prompt) 啟動 REPL | claude "explain this project" |
claude -p "query" | 列印模式 (Print Mode) - 執行查詢後退出 | claude -p "explain this function" |
cat file | claude -p "query" | 處理管道傳送的內容 (Piped Content) | cat logs.txt | claude -p "explain" |
claude -c | 繼續最近的對話 | claude -c |
claude -c -p "query" | 在列印模式下繼續對話 | claude -c -p "check for type errors" |
claude -r "<session>" "query" | 依 ID 或名稱恢復工作階段 (Resume Session) | claude -r "auth-refactor" "finish this PR" |
claude update | 更新至最新版本 | claude update |
/doctor (斜線指令) | 診斷安裝、設定檔與外掛程式 (Plugins) 的健康狀態。自 v2.1.116 起可在 Claude 回應的同時開啟,內嵌顯示狀態圖示,並接受按下 f 鍵自動修復檢測到的問題。v2.1.178 將版面配置更新為具有更清晰狀態圖示與高亮指令的扁平樹狀結構 | 在 REPL 內部執行 /doctor |
claude mcp | 設定 MCP 伺服器 (包含用於驗證的 login/logout,v2.1.186+) | 參見 MCP 文件 |
claude mcp serve | 將 Claude Code 作為 MCP 伺服器執行 | claude mcp serve |
claude agents | 開啟 代理檢視 (Agent View) (研究預覽版 / Research Preview,v2.1.139+) — 列出每個 Claude Code 工作階段及其狀態的多工作階段管理器。詳見下方的 代理檢視 (Agent View) | claude agents |
claude auto-mode defaults | 以 JSON 格式印出自動模式 (Auto Mode) 預設規則 | claude auto-mode defaults |
claude auto-mode reset | 還原預設的自動模式設定,附帶確認提示(使用 --yes 可跳過)(v2.1.212) | claude auto-mode reset --yes |
claude --remote-control [name] | 啟動遠端控制 (Remote Control)(為旗標而非子指令;別名 --rc) | claude --rc |
claude plugin | 管理外掛程式 (Plugins)(安裝、啟用、停用) | claude plugin install my-plugin |
claude plugin init <name> | 在 ~/.claude/skills/<name>/ (使用者全域) 建立新外掛程式骨架 — 在下個工作階段自動載入為 <name>@skills-dir,不需要市集 (Marketplace) (v2.1.157+) | claude plugin init my-plugin |
claude plugin tag [path] | 為位於 [path] 的外掛程式建立 {name}--v{version} 發行 git 標籤 (Tag),驗證 plugin.json 與任何包含它的市集條目是否一致 (v2.1.118+) | claude plugin tag ./my-plugin |
claude install [version] | 安裝特定的原生二進位版本。接受 stable、latest 或明確的版本字串 | claude install 2.1.131 |
claude project purge [path] | 刪除專案的所有本地 Claude Code 狀態(逐字稿 Transcript、任務 Tasks、除錯日誌 Debug Logs、檔案編輯歷史、提示詞歷史以及 ~/.claude.json 條目)。省略 [path] 可使用互動式選擇器。旗標:--dry-run 用於預覽,-y/--yes 用於跳過確認,-i/--interactive 用於逐項確認,--all 用於所有專案 (v2.1.126+) | claude project purge ~/work/repo --dry-run |
claude plugin prune | 清除孤立的自動安裝外掛程式依賴(主外掛程式已移除)。plugin uninstall --prune 會在解除安裝目標後執行相同的串接清理 (v2.1.121+) | claude plugin prune |
claude ultrareview [target] | 以非互動方式執行 /ultrareview。將發現結果印至 stdout,成功退出為 0 / 失敗退出為 1。使用 --json 取得原始載荷 (Raw Payload),使用 --timeout <minutes> 覆寫預設的 30 分鐘,使用 --post / --no-post 控制是否將發現結果發回 PR。需要 Claude Code v2.1.227 或更高版本 | claude ultrareview 1234 --json --no-post |
claude self-hosted-runner <setup|doctor|orchestrator> | 將您自己的機器或容器轉變為可執行 Claude Code 網頁、行動端與桌面端工作階段的地方。setup 配置執行器 (Runner),doctor 進行診斷,orchestrator 執行協調程序。團隊 (Team) 與企業 (Enterprise) 方案;需要 Claude Code v2.1.224 或更高版本。 在 Windows 上啟動需要明確的 --base-dir (v2.1.229) | claude self-hosted-runner setup |
claude auth login | 登入(支援 --email、--sso)。自 v2.1.126 起,當瀏覽器回傳無法到達 localhost (WSL2、SSH、容器) 時,接受貼入終端機的 OAuth 代碼作為備用方案 | claude auth login --email user@example.com |
claude auth logout | 登出當前帳號 | claude auth logout |
claude auth status | 檢查驗證狀態 (已登入退出為 0,未登入為 1) | claude auth status |
核心旗標 (Core Flags)
| 旗標 (Flag) | 說明 (Description) | 範例 (Example) |
|---|---|---|
-p, --print | 在非互動模式下印出回應 | claude -p "query" |
-c, --continue | 載入最近的對話 | claude --continue |
-r, --resume | 依 ID 或名稱恢復特定的工作階段 | claude --resume auth-refactor |
-v, --version | 輸出版本號 | claude -v |
-w, --worktree | 在隔離的 git 工作樹 (Worktree) 中啟動。自 v2.1.233 起除了 GitHub PR URL 外也接受 GitLab merge-request URL | claude -w |
-n, --name | 工作階段顯示名稱 | claude -n "auth-refactor" |
--from-pr <url-or-number> | 恢復連結至拉取/合併請求 (Pull/Merge Request) 的工作階段。自 v2.1.119 起接受 GitHub (雲端 + 企業版)、GitLab MR 與 Bitbucket PR URL;先前僅限 GitHub.com | claude --from-pr 42 或 claude --from-pr https://gitlab.example.com/org/repo/-/merge_requests/17 |
--cloud [description|session_id|url] | 在 claude.ai 上建立具有給定描述的雲端工作階段 (Cloud Session),或透過工作階段 ID 或 claude.ai/code URL 附加至現有工作階段 | claude --cloud "implement API" |
--remote "task" | --cloud 的已棄用別名 (Deprecated Alias),包含現有工作階段形式。請改用 --cloud | claude --remote "implement API" |
--remote-control, --rc | 使用遠端控制 (Remote Control) 的互動式工作階段 | claude --rc |
--teleport [session] | 在本地恢復網頁工作階段。裸形式會開啟網頁工作階段選擇器;傳入工作階段 ID 可直接恢復該工作階段。需要 claude.ai 訂閱 | claude --teleport |
--teammate-mode | 代理團隊 (Agent Team) 顯示模式 | claude --teammate-mode tmux |
--bare | 最小模式 (跳過 Hooks、Skills、Plugins、MCP、Auto Memory、CLAUDE.md) | claude --bare |
--safe-mode | 在停用所有自訂設定 (CLAUDE.md、Plugins、Skills、Hooks、MCP) 的情況下啟動,以隔離設定問題;亦可使用 CLAUDE_CODE_SAFE_MODE=1 (v2.1.169) | claude --safe-mode |
--restricted | 鎖定工作階段以供不受信任或共享的使用:移除內建的指令與程式碼執行工具及 WebFetch,忽略使用者/專案/本地設定,將檔案工具限制在工作目錄內,並拒絕 bypassPermissions 與雲端工作階段。亦可使用 CLAUDE_CODE_RESTRICTED=1 (v2.1.248+) | claude --restricted -p "summarize this repo" |
--permission-mode auto | 在自動權限模式 (Auto Permission Mode) 下啟動(取代已移除的 --enable-auto-mode 旗標,自 v2.1.111 起移除) | claude --permission-mode auto |
--channels | 訂閱 MCP 頻道外掛程式 (Channel Plugins)。條目必須標記為 plugin:<name>@<marketplace>;裸名稱會被拒絕 | claude --channels plugin:discord@my-marketplace |
--chrome / --no-chrome | 啟用/停用 Chrome 瀏覽器整合 | claude --chrome |
--effort | 設定思考努力程度 (Effort Level) | claude --effort high |
--init / --init-only | 執行初始化 Hooks | claude --init |
--maintenance | 執行維護 Hooks 並退出 | claude --maintenance |
--disable-slash-commands | 停用所有技能 (Skills) 與斜線指令 (Slash Commands) | claude --disable-slash-commands |
--no-session-persistence | 停用工作階段儲存 (列印模式) | claude -p --no-session-persistence "query" |
--exclude-dynamic-system-prompt-sections | 從系統提示詞中排除動態區段,以提高提示詞快取命中率 (Prompt Cache Hit Rates) | claude -p --exclude-dynamic-system-prompt-sections "query" |
受限模式 (--restricted, v2.1.248+)
--restricted(或 CLAUDE_CODE_RESTRICTED=1)用於代表您無法控制其輸入的人執行 claude — 例如共享機器上的評估套件 (Evaluation Harness)、由外部貢獻者觸發的 CI 作業、演示箱 (Demo Box)。它會套用以下所有限制:
- 移除執行指令或程式碼的工具 — Bash、PowerShell 與 REPL — 以及 WebFetch,除非
--tools明確指定它們。 - 忽略使用者、專案與本地設定檔。 受控設定與明確的
--settings檔案仍然有效,因此管理者可保持控制,而簽入的.claude/settings.json無法擴大沙盒。 - 將檔案工具限制在工作目錄內,使讀取與寫入無法逃脫您啟動時的路徑。
- 拒絕
bypassPermissions,無論其以何種方式請求。 - 拒絕建立雲端工作階段,使受限的執行無法將工作推送到機器之外。
# 評估套件:無 Shell、無網路抓取、無設定繼承
claude --restricted -p "summarize the architecture of this repo"
# 相同的鎖定,但刻意重新啟用一個工具
claude --restricted --tools WebFetch -p "check the linked RFC"注意:
--restricted是比--permission-mode更粗粒度的鎖定。它會直接移除工具而不是提示請求許可,因此受限的工作階段無法從內部擴大權限。
互動模式與列印模式對比 (Interactive vs Print Mode)
graph LR
A["claude"] -->|預設 (Default)| B["互動式 REPL (Interactive REPL)"]
A -->|"-p 旗標"| C["列印模式 (Print Mode)"]
B -->|特性 (Features)| D["多輪對話 (Multi-turn conversation)<br>Tab 補全 (Tab completion)<br>歷史紀錄 (History)<br>斜線指令 (Slash commands)"]
C -->|特性 (Features)| E["單一查詢 (Single query)<br>可腳本化 (Scriptable)<br>可管道傳送 (Pipeable)<br>JSON 輸出 (JSON output)"]互動模式 (Interactive Mode)(預設):
# 啟動互動式工作階段
claude
# 使用初始提示詞啟動
claude "explain the authentication flow"列印模式 (Print Mode)(非互動式):
# 單一查詢後退出
claude -p "what does this function do?"
# 處理檔案內容
cat error.log | claude -p "explain this error"
# 與其他工具串接
claude -p "list todos" | grep "URGENT"模型與設定 (Model & Configuration)
| 旗標 (Flag) | 說明 (Description) | 範例 (Example) |
|---|---|---|
--model | 設定模型 (sonnet, opus, haiku 或全名) | claude --model opus |
--fallback-model | 當主要模型過載/不可用時自動切換備用模型;最多透過 fallbackModel 設定配置三個。自 v2.1.166 起也套用於互動式工作階段(先前僅限列印模式) | claude -p --fallback-model sonnet "query" |
--agent | 指定工作階段的代理 (Agent) | claude --agent my-custom-agent |
--agents | 透過 JSON 定義自訂子代理 (Subagents) | 參見 代理設定 |
--effort | 設定努力程度 (low, medium, high, xhigh, max) | claude --effort xhigh |
模型選擇範例 (Model Selection Examples)
# 將 Opus 5 用於複雜任務
claude --model opus "design a caching strategy"
# 將 Haiku 4.5 用於快速任務
claude --model haiku -p "format this JSON"
# 使用完整的模型名稱
claude --model claude-sonnet-4-6-20250929 "review this code"
# 搭配備用模型以提高可靠性
claude -p --model opus --fallback-model sonnet "analyze architecture"
# 使用 opusplan (Opus 規劃,Sonnet 執行)
claude --model opusplan "design and implement the caching layer"閘道模型探索 (Gateway model discovery, v2.1.129+, 選項開啟):當
ANTHROPIC_BASE_URL指向相容於 Anthropic 的閘道時,設定CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1可從閘道的/v1/models端點填充/model。若無該環境變數,/model將回退至內建的靜態列表。該旗標為選項開啟(Opt-in,在 v2.1.129 中修改),因為探索呼叫可能會顯示使用者無權使用的模型;v2.1.126 曾將其改為隱式,後該行為被復原。
組織預設模型 (Org default model, v2.1.196):當組織管理者設定預設模型時,
/model會將其標記為 "Org default"(或 "Role default")。
系統提示詞自訂 (System Prompt Customization)
| 旗標 (Flag) | 說明 (Description) | 範例 (Example) |
|---|---|---|
--system-prompt | 替換整個預設提示詞 | claude --system-prompt "You are a Python expert" |
--system-prompt-file | 從檔案載入提示詞 (列印模式) | claude -p --system-prompt-file ./prompt.txt "query" |
--append-system-prompt | 附加至預設提示詞後方 | claude --append-system-prompt "Always use TypeScript" |
--append-subagent-system-prompt | 將文字附加至每個子代理的系統提示詞 (非互動式) | claude -p --append-subagent-system-prompt "Cite sources" "query" |
--append-subagent-system-prompt-file | (v2.1.261) 改從檔案載入該附加文字,適用於過長而無法在命令行傳入的提示詞。僅限非互動式,且不能與 --append-subagent-system-prompt 組合使用 | claude -p --append-subagent-system-prompt-file ./subagent-rules.txt "query" |
系統提示詞範例 (System Prompt Examples)
# 完全自訂角色
claude --system-prompt "You are a senior security engineer. Focus on vulnerabilities."
# 附加特定指令
claude --append-system-prompt "Always include unit tests with code examples"
# 從檔案載入複雜提示詞
claude -p --system-prompt-file ./prompts/code-reviewer.txt "review main.py"系統提示詞旗標比較 (System Prompt Flags Comparison)
| 旗標 (Flag) | 行為 (Behavior) | 互動式 (Interactive) | 列印模式 (Print) |
|---|---|---|---|
--system-prompt | 替換整個預設系統提示詞 | ✅ | ✅ |
--system-prompt-file | 以檔案中的提示詞替換 | ❌ | ✅ |
--append-system-prompt | 附加至預設系統提示詞 | ✅ | ✅ |
僅在列印模式下使用 --system-prompt-file。對於互動模式,請使用 --system-prompt 或 --append-system-prompt。
工具與權限管理 (Tool & Permission Management)
| 旗標 (Flag) | 說明 (Description) | 範例 (Example) |
|---|---|---|
--tools | 限制可用的內建工具 | claude -p --tools "Bash,Edit,Read" "query" |
--allowedTools | 無需提示即可執行的工具 | "Bash(git log:*)" "Read" |
--disallowedTools | 從脈絡 (Context) 中移除的工具 | "Bash(rm:*)" "Edit" |
--dangerously-skip-permissions | 跳過所有權限提示 (Permission Prompts) | claude --dangerously-skip-permissions |
--permission-mode | 在指定的權限模式下開始 | claude --permission-mode auto |
--permission-prompt-tool | 用於權限處理的 MCP 工具 | claude -p --permission-prompt-tool mcp_auth "query" |
--permission-prompts | (v2.1.259) 在列印模式下由誰回答權限提示。預設的 host 會傳送給 Agent SDK 主機或 --permission-prompt-tool 工具;當無人能回答時傳入 none,Claude Code 將改為拒絕它們 | claude -p --permission-prompts none "query" |
v2.1.111 更新:
--enable-auto-mode已被移除;自動模式現已預設包含在Shift+Tab切換循環中 — 使用--permission-mode auto可直接在該模式下啟動。
Glob / Grep 腳註 (v2.1.113+):在原生 macOS/Linux 建置版中,
Glob與Grep作為嵌入式的bfs和ugrep二進位檔提供,透過 Bash 工具呼叫而非作為獨立的一等工具。Windows 與 npm 打包的 (JS) 安裝版仍將其作為獨立工具公開。對於子代理的allowedTools/disallowedTools列表,後端替換是透明的 — 您可以在每個平台上的設定中繼續引用Glob/Grep。
PowerShell 自動批准 (v2.1.119):PowerShell 工具指令可以像 Bash 指令一樣在權限模式下自動批准。使用與
Bash(...)規則相同的比對器語法來限定 PowerShell 權限範圍 — 例如PowerShell(Get-ChildItem:*)。
恢復時遵循
--permission-mode(v2.1.132+):claude -p --continue --permission-mode plan(以及--resume)現在會遵循該旗標。早期版本在恢復工作階段時會默默丟棄--permission-mode,導致恢復的計劃模式工作階段在未重新傳遞旗標時默默降級 — 這已修復。
權限強化 (v2.1.214):使用 Daemon 重導向旗標(例如
--url、--connection、--identity)的 Docker/Podman 指令現在需要權限提示而不會自動執行。使用-m/--magic-file或-f/--files-from的file指令現在也需要權限。超過 10,000 個字元的 Bash 指令總是會提示尋求許可,無論允許規則為何。
權限範例 (Permission Examples)
# 用於程式碼審查的唯讀模式
claude --permission-mode plan "review this codebase"
# 僅限安全的工具
claude --tools "Read,Grep,Glob" -p "find all TODO comments"
# 允許特定的 git 指令且無需提示
claude --allowedTools "Bash(git status:*)" "Bash(git log:*)"
# 封鎖危險操作
claude --disallowedTools "Bash(rm -rf:*)" "Bash(git push --force:*)"參數比對
Tool(param:value)(v2.1.178):權限規則遵循Tool(每次使用)或Tool(specifier)的格式。自 v2.1.178 起,指定符 (Specifier) 可以比對工具的輸入參數,而不僅僅是指令或路徑模式 — 使用支援萬用字元 (Wildcard) 的Tool(param:value)形式。這推廣了您已在Bash(...)指令字首(例如Bash(npm run test *))與Read(...)路徑 Glob(例如Read(./.env.*))中使用的比對,以便其他工具可以透過其引數來限定範圍。在撰寫規則之前,請檢查 權限參考指南 (Permissions Reference) 以獲取當前每個工具的範例字串,因為確切的參數名稱因工具而異。
輸出與格式 (Output & Format)
| 旗標 (Flag) | 說明 (Description) | 選項 (Options) | 範例 (Example) |
|---|---|---|---|
--output-format | 指定輸出格式 (列印模式) | text, json, stream-json | claude -p --output-format json "query" |
--input-format | 指定輸入格式 (列印模式) | text, stream-json | claude -p --input-format stream-json |
--verbose | 啟用詳細日誌紀錄 (Verbose Logging) | claude --verbose | |
--include-partial-messages | 包含串流事件 (Streaming Events) | 需要 stream-json | claude -p --output-format stream-json --include-partial-messages "query" |
--forward-subagent-text | 將子代理文字輸出轉發至串流中。自 v2.1.219 起,深度為 2 或更深的子代理也會被轉發,並由其產生的 Agent tool_use id 鍵值識別(這是在預設透過 CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH 啟用的情況下觀察巢狀結構的方式) | 需要 stream-json | claude -p --output-format stream-json --forward-subagent-text "query" |
--json-schema | 取得符合 Schema 的驗證 JSON | claude -p --json-schema '{"type":"object"}' "query" | |
--max-budget-usd | 列印模式的最高花費。自 v2.1.217 起,達到上限也會停止正在執行的背景子代理並拒絕新的衍生 (先前背景代理會繼續執行並超出上限) | claude -p --max-budget-usd 5.00 "query" |
輸出格式範例 (Output Format Examples)
# 純文字 (預設)
claude -p "explain this code"
# 用於程式化使用的 JSON
claude -p --output-format json "list all functions in main.py"
# 用於即時處理的串流 JSON (Streaming JSON)
claude -p --output-format stream-json "generate a long report"
# 帶有 Schema 驗證的結構化輸出
claude -p --json-schema '{"type":"object","properties":{"bugs":{"type":"array"}}}' \
"find bugs in this code and return as JSON"工作區與目錄 (Workspace & Directory)
| 旗標 (Flag) | 說明 (Description) | 範例 (Example) |
|---|---|---|
--add-dir | 新增額外的工作目錄 | claude --add-dir ../apps ../lib |
--setting-sources | 以逗號分隔的設定來源列表 | claude --setting-sources user,project |
/config持久化 (v2.1.119):透過/config指令以互動方式進行的修改,現在會寫入~/.claude/settings.json並參與正常的優先權鏈(策略 Policy → 本地 Local → 專案 Project → 使用者 User)。在 v2.1.119 之前,部分/config修改僅限於當前工作階段。完整的優先順序請參見 記憶與設定 (Memory & Settings)。 |--settings| 從檔案或 JSON 載入設定。檔案大小不得超過 2 MiB (v2.1.214) |claude --settings ./settings.json| |--plugin-dir| 從目錄載入外掛程式 (可重複傳遞) |claude --plugin-dir ./my-plugin|
多目錄範例 (Multi-Directory Example)
# 跨多個專案目錄工作
claude --add-dir ../frontend ../backend ../shared "find all API endpoints"
# 載入自訂設定
claude --settings '{"model":"opus","verbose":true}' "complex task"MCP 設定 (MCP Configuration)
| 旗標 (Flag) | 說明 (Description) | 範例 (Example) |
|---|---|---|
--mcp-config | 從 JSON 載入 MCP 伺服器 | claude --mcp-config ./mcp.json |
--strict-mcp-config | 僅使用指定的 MCP 設定 | claude --strict-mcp-config --mcp-config ./mcp.json |
--channels | 訂閱 MCP 頻道外掛程式 (Channel Plugins)。條目必須標記為 plugin:<name>@<marketplace>;裸名稱會被拒絕 | claude --channels plugin:discord@my-marketplace |
MCP 範例 (MCP Examples)
# 載入 GitHub MCP 伺服器
claude --mcp-config ./github-mcp.json "list open PRs"
# 嚴格模式 - 僅限指定的伺服器
claude --strict-mcp-config --mcp-config ./production-mcp.json "deploy to staging"工作階段管理 (Session Management)
| 旗標 (Flag) | 說明 (Description) | 範例 (Example) |
|---|---|---|
--session-id | 使用特定的工作階段 ID (UUID) | claude --session-id "550e8400-..." |
--fork-session | 恢復時建立新工作階段 | claude --resume abc123 --fork-session |
工作階段範例 (Session Examples)
# 繼續上次對話
claude -c
# 恢復具名工作階段
claude -r "feature-auth" "continue implementing login"
# 分叉工作階段以進行實驗 (Fork Session)
claude --resume feature-auth --fork-session "try alternative approach"
# 使用特定的工作階段 ID
claude --session-id "550e8400-e29b-41d4-a716-446655440000" "continue"工作階段分叉 (Session Fork)
從現有工作階段建立分支以進行實驗:
# 分叉工作階段以嘗試不同方法
claude --resume abc123 --fork-session "try alternative implementation"
# 帶有自訂訊息的分叉
claude -r "feature-auth" --fork-session "test with different architecture"使用場景 (Use Cases):
- 嘗試替代實作方法而不遺失原始工作階段
- 並行實驗不同的做法
- 從成功的成果建立分支以進行變體測試
- 在不影響主工作階段的情況下測試破壞性變更 (Breaking Changes)
原始工作階段保持不變,分叉則成為新的獨立工作階段。
專案狀態清理 (Project State Cleanup, v2.1.126+)
claude project purge 會刪除專案的所有本地 Claude Code 狀態 — 逐字稿、任務列表、除錯日誌、檔案編輯歷史、提示詞歷史行以及專案的 ~/.claude.json 條目。請先使用 --dry-run 來預覽刪除;--all 會巡覽機器上的每個專案。
# 預覽將被刪除的內容 (安全)
claude project purge ~/work/repo --dry-run
# 刪除特定專案的狀態,無提示
claude project purge ~/work/repo --yes
# 互動式巡覽每個專案
claude project purge --all --interactive進階功能 (Advanced Features)
| 旗標 (Flag) | 說明 (Description) | 範例 (Example) |
|---|---|---|
--chrome | 啟用 Chrome 瀏覽器整合 | claude --chrome |
--no-chrome | 停用 Chrome 瀏覽器整合 | claude --no-chrome |
--ide | 可用時自動連接至 IDE | claude --ide |
--max-turns | 限制代理輪數 (Agentic Turns,非互動式) | claude -p --max-turns 3 "query" |
--debug | 啟用帶有過濾功能的除錯模式 | claude --debug "api,mcp" |
--enable-lsp-logging | 啟用詳細的 LSP 日誌紀錄 | claude --enable-lsp-logging |
--betas | API 請求的 Beta 標頭 | claude --betas interleaved-thinking |
--plugin-dir | 從目錄載入外掛程式 (可重複傳遞) | claude --plugin-dir ./my-plugin |
--effort | 設定思考努力程度 (Effort Level) | claude --effort high |
--bare | 最小模式 (跳過 Hooks、Skills、Plugins、MCP、Auto Memory、CLAUDE.md) | claude --bare |
--channels | 訂閱 MCP 頻道外掛程式 (標記為 plugin:<name>@<marketplace>) | claude --channels plugin:discord@my-marketplace |
--tmux | 為工作樹建立 tmux 工作階段 | claude --tmux |
--fork-session | 恢復時建立新的工作階段 ID | claude --resume abc --fork-session |
--max-budget-usd | 最高花費 (列印模式);達到時亦會停止背景子代理 (v2.1.217) | claude -p --max-budget-usd 5.00 "query" |
--json-schema | 經過驗證的 JSON 輸出 | claude -p --json-schema '{"type":"object"}' "q" |
--ax-screen-reader | 供螢幕閱讀器使用的純文字轉譯模式 (v2.1.208) | claude --ax-screen-reader |
平台與主題備註 (Platform & Theme Notes, v2.1.112)
- Windows 上的 PowerShell 工具:專用的 PowerShell 工具正在 Windows 上推出,並可透過環境變數控制。
- Auto (匹配終端機) 主題:新的 "Auto (match terminal)" 主題會將 Claude Code 的淺色/深色外觀與您的終端機同步。
- 更安靜的權限提示:唯讀的
Bash呼叫與Glob模式不再觸發權限提示。
進階範例 (Advanced Examples)
# 限制自主動作
claude -p --max-turns 5 "refactor this module"
# 除錯 API 呼叫
claude --debug "api" "test query"
# 啟用 IDE 整合
claude --ide "help me with this file"代理設定 (Agents Configuration)
--agents 旗標接受定義工作階段自訂子代理 (Subagents) 的 JSON 物件。
自 v2.1.243 起,--agents 不再默默忽略無效的 JSON 或無效的代理定義 — 它會帶著清晰的錯誤退出,與 --mcp-config 原本的行為一致。
代理 JSON 格式 (Agents JSON Format)
{
"agent-name": {
"description": "Required: when to invoke this agent",
"prompt": "Required: system prompt for the agent",
"tools": ["Optional", "array", "of", "tools"],
"model": "optional: sonnet|opus|haiku"
}
}必填欄位 (Required Fields):
description- 描述何時使用此代理的自然語言說明prompt- 定義代理角色與行為的系統提示詞
選填欄位 (Optional Fields):
tools- 可用工具陣列(若省略則繼承所有工具)- 格式:
["Read", "Grep", "Glob", "Bash"]
- 格式:
model- 使用的模型:sonnet、opus或haiku
完整代理範例 (Complete Agents Example)
{
"code-reviewer": {
"description": "Expert code reviewer. Use proactively after code changes.",
"prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
"tools": ["Read", "Grep", "Glob", "Bash"],
"model": "sonnet"
},
"debugger": {
"description": "Debugging specialist for errors and test failures.",
"prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes.",
"tools": ["Read", "Edit", "Bash", "Grep"],
"model": "opus"
},
"documenter": {
"description": "Documentation specialist for generating guides.",
"prompt": "You are a technical writer. Create clear, comprehensive documentation.",
"tools": ["Read", "Write"],
"model": "haiku"
}
}代理指令範例 (Agents Command Examples)
# 內嵌定義自訂代理
claude --agents '{
"security-auditor": {
"description": "Security specialist for vulnerability analysis",
"prompt": "You are a security expert. Find vulnerabilities and suggest fixes.",
"tools": ["Read", "Grep", "Glob"],
"model": "opus"
}
}' "audit this codebase for security issues"
# 從檔案載入代理
claude --agents "$(cat ~/.claude/agents.json)" "review the auth module"
# 與其他旗標組合使用
claude -p --agents "$(cat agents.json)" --model sonnet "analyze performance"代理優先順序 (Agent Priority)
當存在多個代理定義時,會依以下優先順序載入:
- CLI 定義 (
--agents旗標) - 特定於工作階段 - 專案層級 (
.claude/agents/) - 當前專案 - 使用者層級 (
~/.claude/agents/) - 所有專案
CLI 定義的代理在工作階段中會覆寫專案與使用者層級的代理。專案層級代理在名稱衝突時會覆寫使用者層級代理。有關包含外掛程式層級代理在內的完整優先順序表,請參見 課程 04 — 子代理 (Subagents)。
代理檢視 (Agent View, claude agents, v2.1.139+)
研究預覽版 (Research Preview) — 功能已足夠穩定可用於日常,但未來可能會有所變動。
claude agents 會開啟 代理檢視 (Agent View) — 這是一個列出機器上每個 Claude Code 工作階段及其當前狀態 (running 執行中、blocked on you 等待您的回應、done 已完成) 的單一列表。它是您在執行背景代理、排程任務或 --bg 啟動的工作階段時,取代頻繁切換多個終端機分頁的解決方案。
# 開啟代理檢視 (Agent View)
claude agents當您從檢視中(或透過 claude --bg <prompt>)發派工作階段時,可以傳遞與傳給 claude 本身相同的設定旗標。為代理檢視發派路徑引入的旗標包括:
| 旗標 (Flag) | 自版本起 | 說明 (Description) |
|---|---|---|
--cwd <path> | v2.1.141 | 將工作階段列表 (或新工作階段) 的範圍限定於特定工作目錄 |
--add-dir <path> | v2.1.142 | 將目錄新增至發派工作階段的工作區 |
--settings <path> | v2.1.142 | 為發派的工作階段使用特定的 settings.json |
--mcp-config <path> | v2.1.142 | 為發派的工作階段使用特定的 MCP 設定 |
--plugin-dir <path> | v2.1.142 | 為發派的工作階段使用特定的外掛程式目錄 |
--permission-mode <mode> | v2.1.142 | 設定發派工作階段的權限模式 (plan、acceptEdits、auto 等) |
--model <model> | v2.1.142 | 為發派的工作階段固定模型 |
--effort <level> | v2.1.142 | 固定努力程度 (low/medium/high/xhigh/max) |
--dangerously-skip-permissions | v2.1.142 | 在沒有權限提示的情況下執行發派的工作階段 (僅限在沙盒中使用) |
--json | v2.1.145 | 將代理列表印出為機器可讀的 JSON,以供腳本使用 (狀態列、工作階段選擇器、tmux-resurrect 整合) |
完成工作但留有背景 Shell 開啟的工作階段會從 "Working" 移動到 "Completed" (v2.1.141 修復)。在附加的代理工作階段中,Shift+Tab 可切換包含自動模式在內的權限模式 (v2.1.143)。
GitLab 合併請求 (v2.1.233) — 代理檢視現在能識別 GitLab MR URL 與 GitHub PR URL,並將合併請求顯示為 !N (GitHub 拉取請求保持為 #N)。同一版本也讓 --worktree 能夠接受 GitLab MR URL。
釘選工作階段 (Pin a session) — 在 claude agents 中的工作階段按下 Ctrl+T 即可釘選它 (v2.1.147)。釘選的背景工作階段在閒置時會保持存活、原地重啟以套用 Claude Code 更新,且僅會在無釘選工作階段之後才因記憶體壓力被釋放。(此 Ctrl+T 的範圍僅限於代理檢視;在主工作階段中它會切換任務列表檢視。)
高價值使用場景 (High-Value Use Cases)
1. CI/CD 整合 (CI/CD Integration)
在您的 CI/CD 管線中使用 Claude Code 進行自動化的程式碼審查、測試與文件撰寫。
GitHub Actions 範例:
name: AI Code Review
on: [pull_request]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Claude Code
run: npm install -g @anthropic-ai/claude-code
- name: Run Code Review
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
claude -p --output-format json \
--max-turns 1 \
"Review the changes in this PR for:
- Security vulnerabilities
- Performance issues
- Code quality
Output as JSON with 'issues' array" > review.json
- name: Post Review Comment
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const review = JSON.parse(fs.readFileSync('review.json', 'utf8'));
// Process and post review commentsJenkins 管線 (Jenkins Pipeline):
pipeline {
agent any
stages {
stage('AI Review') {
steps {
sh '''
claude -p --output-format json \
--max-turns 3 \
"Analyze test coverage and suggest missing tests" \
> coverage-analysis.json
'''
}
}
}
}無頭 (Headless) ultrareview (需要 v2.1.227+):
# .github/workflows/ultrareview.yml
- name: Claude ultrareview
run: claude ultrareview ${{ github.event.pull_request.number }} --json --no-post > review.jsonclaude ultrareview 在審查乾淨時退出為 0,有回報發現時退出為 1,因此它是即插即用的 PR 關卡。使用 --timeout <minutes> 可覆寫預設的 30 分鐘。--post 會將完成的發現發布至拉取請求;--no-post 則僅保留在 stdout 中,這適合在後續 CI 步驟自行格式化報告時使用。
2. 腳本管道傳送 (Script Piping)
將檔案、日誌與資料透過管道傳送給 Claude 進行分析。
日誌分析 (Log Analysis):
# 分析錯誤日誌
tail -1000 /var/log/app/error.log | claude -p "summarize these errors and suggest fixes"
# 尋找存取日誌中的模式
cat access.log | claude -p "identify suspicious access patterns"
# 分析 git 歷史紀錄
git log --oneline -50 | claude -p "summarize recent development activity"程式碼處理 (Code Processing):
# 審查特定檔案
cat src/auth.ts | claude -p "review this authentication code for security issues"
# 生成文件
cat src/api/*.ts | claude -p "generate API documentation in markdown"
# 尋找 TODO 並排序優先順序
grep -r "TODO" src/ | claude -p "prioritize these TODOs by importance"3. 多工作階段工作流程 (Multi-Session Workflows)
使用多個對話執行緒管理複雜專案。
# 啟動功能分支工作階段
claude -r "feature-auth" "let's implement user authentication"
# 稍後繼續該工作階段
claude -r "feature-auth" "add password reset functionality"
# 分叉以嘗試替代方法
claude --resume feature-auth --fork-session "try OAuth instead"
# 在不同的功能工作階段之間切換
claude -r "feature-payments" "continue with Stripe integration"4. 自訂代理設定 (Custom Agent Configuration)
為您團隊的工作流程定義專用的代理。
# 將代理設定儲存至檔案
cat > ~/.claude/agents.json << 'EOF'
{
"reviewer": {
"description": "Code reviewer for PR reviews",
"prompt": "Review code for quality, security, and maintainability.",
"model": "opus"
},
"documenter": {
"description": "Documentation specialist",
"prompt": "Generate clear, comprehensive documentation.",
"model": "sonnet"
},
"refactorer": {
"description": "Code refactoring expert",
"prompt": "Suggest and implement clean code refactoring.",
"tools": ["Read", "Edit", "Glob"]
}
}
EOF
# 在工作階段中使用代理
claude --agents "$(cat ~/.claude/agents.json)" "review the auth module"5. 批次處理 (Batch Processing)
使用一致的設定處理多個查詢。
# 處理多個檔案
for file in src/*.ts; do
echo "Processing $file..."
claude -p --model haiku "summarize this file: $(cat $file)" >> summaries.md
done
# 批次程式碼審查
find src -name "*.py" -exec sh -c '
echo "## $1" >> review.md
cat "$1" | claude -p "brief code review" >> review.md
' _ {} \;
# 為所有模組生成測試
for module in $(ls src/modules/); do
claude -p "generate unit tests for src/modules/$module" > "tests/$module.test.ts"
done6. 安全意識開發 (Security-Conscious Development)
使用權限控制進行安全操作。
# 唯讀安全性審計
claude --permission-mode plan \
--tools "Read,Grep,Glob" \
"audit this codebase for security vulnerabilities"
# 封鎖危險指令
claude --disallowedTools "Bash(rm:*)" "Bash(curl:*)" "Bash(wget:*)" \
"help me clean up this project"
# 受限自動化
claude -p --max-turns 2 \
--allowedTools "Read" "Glob" \
"find all hardcoded credentials"7. JSON API 整合 (JSON API Integration)
搭配 jq 解析,將 Claude 作為可程式化的 API 用於您的工具中。
# 取得結構化分析
claude -p --output-format json \
--json-schema '{"type":"object","properties":{"functions":{"type":"array"},"complexity":{"type":"string"}}}' \
"analyze main.py and return function list with complexity rating"
# 與 jq 整合以進行處理
claude -p --output-format json "list all API endpoints" | jq '.endpoints[]'
# 在腳本中使用
RESULT=$(claude -p --output-format json "is this code secure? answer with {secure: boolean, issues: []}" < code.py)
if echo "$RESULT" | jq -e '.secure == false' > /dev/null; then
echo "Security issues found!"
echo "$RESULT" | jq '.issues[]'
fijq 解析範例 (jq Parsing Examples)
使用 jq 解析並處理 Claude 的 JSON 輸出:
# 提取特定欄位
claude -p --output-format json "analyze this code" | jq '.result'
# 過濾陣列元素
claude -p --output-format json "list issues" | jq -r '.issues[] | select(.severity=="high")'
# 提取多個欄位
claude -p --output-format json "describe the project" | jq -r '.{name, version, description}'
# 轉換為 CSV
claude -p --output-format json "list functions" | jq -r '.functions[] | [.name, .lineCount] | @csv'
# 條件處理
claude -p --output-format json "check security" | jq 'if .vulnerabilities | length > 0 then "UNSAFE" else "SAFE" end'
# 提取巢狀數值
claude -p --output-format json "analyze performance" | jq '.metrics.cpu.usage'
# 處理整個陣列
claude -p --output-format json "find todos" | jq '.todos | length'
# 轉換輸出格式
claude -p --output-format json "list improvements" | jq 'map({title: .title, priority: .priority})'模型 (Models)
Claude Code 支援多種具備不同功能的模型:
| 模型 (Model) | ID | 脈絡視窗 (Context Window) | 備註 (Notes) |
|---|---|---|---|
| Sonnet 5 | claude-sonnet-5 | 1M tokens | Pro / Team Standard / Enterprise 席位的預設模型 (v2.1.197);原生 1M-token 脈絡視窗。自 v2.1.219 起,Opus 5 為 Max、Team Premium、Enterprise 現金積點 (Pay-as-you-go) 與 Anthropic API 上的預設 Opus 模型;Microsoft Foundry 仍將 opus 別名解析為 Opus 4.6 |
| Opus 5 | claude-opus-5 | 1M tokens | Max、Team Premium、Enterprise 現金積點、Anthropic API、AWS 上的 Claude Platform、Amazon Bedrock 以及 Google Cloud Agent Platform 上的預設 Opus 模型 (v2.1.219);自適應努力程度 low → max,預設努力程度為 high |
| Opus 4.8 | claude-opus-4-8 | 1M tokens | 先前的旗艦 Opus 模型,仍可選擇;自適應努力程度 low → max;預設努力程度為 high (v2.1.154) |
| Sonnet 4.6 | claude-sonnet-4-6 | 1M tokens | 平衡速度與能力;Pro/Max 訂閱者的預設努力程度在 v2.1.117 中從 medium 提高至 high |
| Haiku 4.5 | claude-haiku-4-5 | 200K tokens | 最快速,最適合快速任務;不支援努力程度設定 |
| Fable 5.1 | claude-fable-5-1 | — | 當前 Fable 模型;fable 別名會解析至此模型 (v2.1.257) |
| Fable 5 | claude-fable-5 | — | Mythos 級別模型,已調整為一般用途安全模型 (v2.1.170) |
模型選擇 (Model Selection)
# 使用短名稱
claude --model opus "complex architectural review"
claude --model sonnet "implement this feature"
claude --model haiku -p "format this JSON"
# 使用 opusplan 別名 (Opus 規劃,Sonnet 執行)
claude --model opusplan "design and implement the API"
# 在工作階段中切換快速模式 (Fast Mode)
/fastFable 5.1 與
fable別名 (v2.1.257):Fable 5.1 (claude-fable-5-1) 於 v2.1.257 推出,且fable別名現在解析至此模型而非 Fable 5。官方模型設定頁面指出 Fable 5.1 "需要 Claude Code v2.1.255 或更高版本",但 2.1.255 從未發布 — v2.1.257 是使用者實際上能安裝它的第一個版本。在 Claude 應用程式閘道上,fable與best仍解析為 Fable 5;在那裡請在/model中明確選擇 5.1。
快速模式 (Fast Mode) 執行於 Opus 5 與 Opus 4.8 上 (v2.1.219):自 v2.1.219 起,
/fast套用於 Opus 5 與 Opus 4.8 — Opus 4.7 已從快速模式中移除。Opus 5 的快速模式計費為每 Mtok $10/$50。快速模式最初在 v2.1.154 中移至 Opus 4.8(約為標準費率的 2 倍,換取約 2.5 倍的輸出速度),並在 v2.1.142 中從 Opus 4.6 切換為 Opus 4.7。環境變數CLAUDE_CODE_OPUS_4_6_FAST_MODE_OVERRIDE在 v2.1.154 中被棄用並於 2026-06-01 移除;快速模式不再適用於 Opus 4.6 — 請改選 Opus 5 或 Opus 4.8。
努力程度 (Effort Levels - Opus 5 / Sonnet 5 / Opus 4.8 / Opus 4.7)
Opus 5、Sonnet 5、Opus 4.8 與 Opus 4.7 支援自適應推理並可搭配努力程度 (Effort Levels),由輕至重排序為:low (○)、medium (◐)、high (●)、xhigh 與 max。預設在 Opus 5、Sonnet 5、Opus 4.8 (自 v2.1.154 起)、Opus 4.6 與 Sonnet 4.6 上為 high,在 Opus 4.7 上為 xhigh。xhigh 可用於 Opus 5、Sonnet 5、Opus 4.8 與 Opus 4.7;max 可用於 Opus 5、Sonnet 5、Opus 4.8/4.7/4.6 與 Sonnet 4.6 (僅限工作階段)。Haiku 4.5 無努力程度設定。在 Opus 4.6 / Sonnet 4.6 上,Pro/Max 訂閱者的預設努力程度在 v2.1.117 中從 medium 提高至 high。
# 透過 CLI 旗標設定努力程度
claude --effort high "complex review"
# 透過斜線指令設定努力程度
/effort high
# 透過環境變數設定努力程度
export CLAUDE_CODE_EFFORT_LEVEL=high # low, medium, high, xhigh (Opus 5, Sonnet 5, Opus 4.8/4.7), 或 max — 在 Opus 5 上預設為 high提示詞中的 "ultrathink" 關鍵字會啟動深度推理。/effort 選單還提供 ultracode,這不是模型努力程度 — 它會傳送 xhigh 並讓 Claude 協調動態工作流程 (Dynamic Workflows,僅限工作階段)。
關鍵環境變數 (Key Environment Variables)
| 變數 (Variable) | 說明 (Description) |
|---|---|
ANTHROPIC_API_KEY | 用於驗證的 API 金鑰 |
ANTHROPIC_MODEL | 覆寫預設模型 |
ANTHROPIC_DEFAULT_MODEL | (v2.1.236) 設定新工作階段啟動時的模型。與固定模型的 ANTHROPIC_MODEL 不同,在 /model 中選擇仍會覆寫此數值且在重啟後繼續保持 — 這種差異即為該變數的目的。 |
ANTHROPIC_CUSTOM_MODEL_OPTION | API 的自訂模型選項 |
ANTHROPIC_DEFAULT_OPUS_MODEL | 覆寫預設的 Opus 模型 ID |
ANTHROPIC_DEFAULT_SONNET_MODEL | 覆寫預設的 Sonnet 模型 ID |
ANTHROPIC_DEFAULT_HAIKU_MODEL | 覆寫預設的 Haiku 模型 ID |
MAX_THINKING_TOKENS | 設定擴充思考 Token 預算 (Extended Thinking Token Budget) |
CLAUDE_CODE_EFFORT_LEVEL | 設定努力程度 (low/medium/high/xhigh/max) — 在 Opus 5、Sonnet 5 與 Opus 4.8 上預設為 high (Opus 4.7 上為 xhigh);xhigh 需要 Opus 5、Sonnet 5 或 Opus 4.8/4.7;max 可在 Opus 5、Sonnet 5、Opus 4.8/4.7/4.6 與 Sonnet 4.6 上運作 |
CLAUDE_CODE_SIMPLE | 最小模式,由 --bare 旗標設定 |
CLAUDE_CODE_SAFE_MODE | 設定為 1 時會在停用所有自訂設定 (CLAUDE.md、Plugins、Skills、Hooks、MCP) 的情況下啟動 — --safe-mode 的環境變數形式,用於隔離設定問題 (v2.1.169) |
CLAUDE_CODE_DISABLE_BUNDLED_SKILLS | 設定為 1 時可對模型隱藏內建技能、工作流程與指令 (v2.1.169) |
CLAUDE_CODE_DISABLE_AUTO_MEMORY | 停用自動 CLAUDE.md 更新 |
CLAUDE_CODE_DISABLE_BACKGROUND_TASKS | 停用背景任務執行 |
CLAUDE_CODE_DISABLE_CRON | 停用排程/Cron 任務 |
CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS | 停用 git 相關指令 |
CLAUDE_CODE_DISABLE_TERMINAL_TITLE | 停用終端機標題更新 |
CLAUDE_CODE_DISABLE_1M_CONTEXT | 停用 1M Token 脈絡視窗 |
CLAUDE_CODE_DISABLE_MOUSE_CLICKS | 停用全螢幕模式下的滑鼠點擊/拖曳/懸停;滾輪捲動仍可運作 (v2.1.195+) |
CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK | 停用非串流備用方案 (Non-streaming Fallback) |
CLAUDE_CODE_ENABLE_TASKS | 啟用任務列表 (Task List) 功能 |
CLAUDE_CODE_TASK_LIST_ID | 跨工作階段共享的具名任務目錄 |
CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION | 切換提示詞建議 (true/false) |
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS | 啟用實驗性代理團隊 (Agent Teams) |
CLAUDE_CODE_NEW_INIT | 使用新的初始化流程 |
CLAUDE_CODE_SUBAGENT_MODEL | 子代理執行的模型 |
CLAUDE_CODE_PLUGIN_SEED_DIR | 外掛程式種子檔 (Plugin Seed Files) 目錄 |
CLAUDE_CODE_SUBPROCESS_ENV_SCRUB | 從子程序中擦除的環境變數 |
CLAUDE_AUTOCOMPACT_PCT_OVERRIDE | 覆寫自動壓縮百分比 (Auto-compaction Percentage) |
CLAUDE_STREAM_IDLE_TIMEOUT_MS | 串流閒置逾時 (以毫秒為單位) |
SLASH_COMMAND_TOOL_CHAR_BUDGET | 斜線指令工具的字元預算 |
ENABLE_TOOL_SEARCH | 啟用工具搜尋功能 |
MAX_MCP_OUTPUT_TOKENS | MCP 工具輸出的最大 Token 數 |
CLAUDE_CODE_PERFORCE_MODE | 設定為 1 以啟用 Perforce 模式 — 預設將檔案視為唯讀 (適用於 Perforce/P4 版本控制工作流程) (新增於 v2.1.98) |
DISABLE_UPDATES | 封鎖包含手動 claude update 在內的所有更新路徑。比僅封鎖背景自動更新器的 DISABLE_AUTOUPDATER 更為嚴格 (v2.1.118+) |
CLAUDE_CODE_HIDE_CWD | 設定為 1 時會在啟動標誌中隱藏當前工作目錄 (隱私 / 螢幕分享用途) (v2.1.119+) |
CLAUDE_CODE_FORK_SUBAGENT | 設定為 1 可在預設關閉之處開啟分叉模式 (Fork Mode):非互動模式 (claude -p)、Agent SDK 或早於 v2.1.232 的 Claude Code。自 v2.1.232 起,分叉模式在所有建置版本的互動式工作階段中預設開啟,無論是否為第一方 (GA v2.1.117) |
CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN | 設定為 1 可退出全螢幕備用螢幕轉譯器 (Alternate-Screen Renderer);工作階段留在正常的終端機捲滾紀錄中。在將逐字稿管道傳送至日誌或與 script(1) 搭配時很有用 (v2.1.132+)。 |
CLAUDE_CODE_SESSION_ID | 在 Claude Code 啟動的每個 Bash 工具子程序中設定;等於 Hook 輸入 JSON 中的 session_id。用於將 Bash 日誌與 Hook 遙測關聯 (v2.1.132+)。 |
CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL | 設定為 1 可為擷取 OpenTelemetry 資料的組織重新啟用 Anthropic 的工作階段品質調查。在 OTEL 部署中預設關閉 (v2.1.136+)。 |
OTEL_LOG_TOOL_DETAILS | 設定為 1 可在 OpenTelemetry 事件中解除自訂與 MCP 指令名稱的遮蔽 (v2.1.117+)。遮蔽仍為預設行為。 |
CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH | 設定套用於 OpenTelemetry 內容屬性的截斷限制 (預設 60 KB) (v2.1.214) |
FORCE_HYPERLINK | 設定為 0 可退出頁尾中可點擊的 PR 徽章超連結,該超連結現在即使無法自動檢測到終端機支援也會轉譯 (v2.1.217) |
ANTHROPIC_BEDROCK_SERVICE_TIER | 選擇 Bedrock 服務層級:default、flex 或 priority (v2.1.122+) |
AI_AGENT | 自動設定於子程序上,以便外部 CLI (例如 gh) 能將流量歸因於 Claude Code (v2.1.120+) |
CLAUDE_CODE_FORCE_SYNC_OUTPUT | 設定為 1 可對自動檢測未涵蓋到的終端機 (例如 Emacs eat) 強制同步輸出 (v2.1.129+) |
CLAUDE_CODE_PACKAGE_MANAGER_AUTO_UPDATE | 設定為 1 可為 Homebrew/WinGet 安裝啟用背景升級 (通常不會自動更新) (v2.1.129+) |
CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY | 當設定 ANTHROPIC_BASE_URL 時,設定為 1 可選擇加入閘道 /v1/models 探索。若無此設定,/model 會顯示內建靜態列表 (v2.1.129+) |
CLAUDE_CODE_ENABLE_AUTO_MODE | 在 Bedrock、Vertex 與 Foundry 上開啟自動模式的舊版選項 (v2.1.158–v2.1.206)。自 v2.1.207 起,自動模式在這些提供者的 Sonnet 5、Opus 4.7/4.8 與 Fable 5 上預設可用 (Opus 5 於 v2.1.219 新增) — 接受此變數是為了相容性,但無效果 |
CLAUDE_CODE_MAX_WEB_SEARCHES_PER_SESSION | 每個工作階段 WebSearch 工具呼叫的上限,以防止失控的搜尋迴圈。預設 200 (v2.1.212) |
CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS | 同時執行的子代理上限。預設 20 (v2.1.217) |
CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH | 控制巢狀子代理引發可以達到的深度。自 v2.1.219 起預設為 3 層 (先前為 1);設定為 1 可完全停用巢狀結構 |
CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS | 長時間執行的 MCP 工具呼叫自動轉入背景前的門檻 (以毫秒為單位)。預設 120000 (2 分鐘) (v2.1.212) |
CLAUDE_AX_SCREEN_READER | 設定為 1 以啟用純文字螢幕閱讀器轉譯模式。與 --ax-screen-reader 或設定中的 "axScreenReader": true 效果相同 (v2.1.208) |
CLAUDE_CLIENT_PRESENCE_FILE | 指向標記檔案,以便在您位於機器前時抑制行動端推送通知 (v2.1.181+)。注意:名稱為 CLAUDE_CLIENT_PRESENCE_FILE,而非 CLAUDE_CODE_CLIENT_PRESENCE_FILE。 |
CLAUDE_CODE_MAX_RETRIES | API 重試嘗試的最大次數。自 v2.1.186 起上限為 15。 |
CLAUDE_CODE_RETRY_WATCHDOG | 建議用於無人值守工作階段的重試控制,作為提高 CLAUDE_CODE_MAX_RETRIES 的替代方案 (v2.1.186+)。 |
CLAUDE_ENABLE_STREAM_WATCHDOG | 串流閒置看門狗 (Streaming Idle Watchdog)(在 5 分鐘無串流事件後中止/重試)對所有提供者預設開啟;設定為 0 可停用 (v2.1.196)。 |
CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT | 覆寫對懸掛且無回應的遠端 MCP 工具呼叫的 5 分鐘閒置中止 (v2.1.187+)。 |
CLAUDE_CODE_OPUS_4_6_FAST_MODE_OVERRIDE | 已移除 (自 v2.1.160 起無效)。 先前將快速模式 (/fast) 固定為 Opus 4.6。自 v2.1.219 起,/fast 僅套用於 Opus 5 與 Opus 4.8 — Opus 4.6 與 Opus 4.7 不再是快速模式目標。 |
CLAUDE_CODE_ENABLE_TODO_TOOLS | 設定為 1 可還原待辦事項/任務追蹤工具 (TaskCreate/Get/Update/List, TodoWrite),這些工具在 Opus 4.8、Sonnet 5、Fable 5、Mythos 5 與更新的模型上不可用 (v2.1.233) |
CLAUDE_CODE_WEBFETCH_CACHE_TTL_MS | WebFetch 快取已抓取 URL 的時間。預設 15 分鐘 (v2.1.233) |
CLAUDE_CODE_TOOL_MEMORY_LIMIT | 僅限 Linux:選擇套用至 Bash 指令的記憶體 cgroup (v2.1.233) |
ANTHROPIC_BEDROCK_REGION_PREFIX | 偏好特定的 Bedrock 跨區域推論設定檔 (Cross-region inference profile) (v2.1.224) |
CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT | 設定為 1 可在未識別的模型 ID 上還原 v2.1.223 之前的自動壓縮行為 (v2.1.223) |
CLAUDE_CODE_WORKFLOW_PREFIX_STAGGER_MS | 設定為 0 可在動態工作流程扇出 (Fan-out) 上停用字首交錯 (v2.1.229) |
CLAUDE_CODE_USER_DIALOG_TIMEOUT_MS | 覆寫 dialogExpiry 設定 (v2.1.224) |
CLAUDE_CODE_PROJECT_DIR_NAME | 覆寫 Claude Code 從專案路徑衍生出來的每個專案逐字稿目錄名稱 (v2.1.234) |
這八列來自變更日誌 (Changelog)。 CLI 參考頁面沒有專用的環境變數區段,因此它們記錄自 v2.1.221–v2.1.234 的變更日誌條目而非參考頁面。
CLAUDE_CODE_DISABLE_1M_CONTEXT在 v2.1.223 中擴大:它現在透過自動壓縮將具備原生 1M Token 視窗的每個 Claude 模型保持在 200K,而不僅僅是固定列表的模型 ID。
Vertex AI 上的
ENABLE_TOOL_SEARCH(v2.1.119+):在 Google Cloud Vertex AI 部署上,工具搜尋預設停用。希望在 Vertex 上使用工具搜尋功能的使用者必須透過export ENABLE_TOOL_SEARCH=true明確選擇加入。在直接 Anthropic API 上,它仍預設為啟用。
Settings.json 鍵值 (Settings.json Keys)
這些鍵值部位於 settings.json 檔案(使用者範圍為 ~/.claude/settings.json,專案範圍為 .claude/settings.json),而非作為旗標或環境變數傳遞。下表涵蓋了一些近期新增的 UI/UX 鍵值;有關託管的 enforceAvailableModels 鍵值,請參見 進階功能 → 託管設定 (Managed Settings)。
| 鍵值 (Key) | 說明 (Description) |
|---|---|
respondToBashCommands | (v2.1.186) 自動回應 ! bash 指令的輸出。預設為 true。設定為 false 可取得僅限脈絡 (v2.1.186 之前) 的行為。參見 進階功能 → Bash 模式。 |
wheelScrollAccelerationEnabled | (v2.1.174) 設定為 false 可停用全螢幕轉譯器中的滑鼠滾輪捲動加速。當快速滾動滾輪過頭時很有用。 |
footerLinksRegexes | (v2.1.176) 在頁尾列中將比對到的連結轉譯為徽章的正則表達式陣列 (Array of regexes)。可在使用者或託管設定中配置。 |
language | 設定 Claude 偏好的回應語言與語音聽寫語言(例如 "french"、"japanese")。自 v2.1.176 起,它也會固定用於自動生成工作階段標題的語言。 |
sandbox.filesystem.disabled | (v2.1.216) 跳過檔案系統沙盒化 (Filesystem Sandboxing),同時保持網路出口控制執行。適用於檔案沙盒打破工具链但網路策略必須保持執行的工作流程。 |
emojiCompletionEnabled | (v2.1.217) 在提示詞輸入中啟用 Emoji 短碼自動補全(例如輸入 :heart: 會插入 ❤️)。設定為 false 可停用。 |
workflowSizeGuideline | (v2.1.219) 從任何設定檔設定建議的動態工作流程規模指南。該指南是 Claude 力求達到的指導方針,而非硬性上限 — 預設為 medium(目標少於 15 個代理),亦可選擇其他規模或不受限制。在此鍵值設定期間,/config 中會隱藏 "Dynamic workflow size" 列。這與 CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS 不同,後者是強制執行的並行限制。 |
spellcheck | (v2.1.235) 使用 PATH 上的 aspell、hunspell 或 ispell(按此順序嘗試)在提示詞輸入中為拼錯的單字加上下劃線。物件值 — {"enabled": true, "language": "en_GB"} — 且預設關閉。僅從使用者設定、--settings 旗標與託管設定讀取:專案 .claude/settings.json 或 .claude/settings.local.json 中的 spellcheck 區塊會被忽略。另請參見 進階功能 → 額外的使用者層級設定。 |
modelPicker | (v2.1.243) 以您自己的順序和標籤選擇 /model 選擇器列出的模型。這是少數跨設定層級替換而非合併的設定之一。 |
promptCacheTtl | (v2.1.243) 為主要對話選擇提示詞快取生存時間 (Prompt Cache Lifetime)。 |
subagentPromptCacheTtl | (v2.1.243) 為主要對話之外的子代理和其他請求選擇相同的選項。 |
modelPricing | (v2.1.243) 託管設定 (Managed Setting)。 提供您組織合約簽訂的費率,以便 /cost、狀態列與遙測報告這些費率而非定價。 |
keybindingFlavor | 自 v2.1.261 起棄用且無效果。 提示詞的單字編輯按鍵總是遵循 readline 慣例,就像 Bash 一樣:Ctrl+W 向後刪除至空白,Alt+F 與 Alt+D 停在單字結尾,標點符號分隔單字。Claude Code 仍然接受該按鍵,因此設定該按鍵的設定檔仍保持有效。(在 v2.1.238–v2.1.260 中,它在 "classic" 與 "readline" 之間選擇。) |
bashOutputMaxChars | (v2.1.261) Claude 內嵌接收的成功 Bash 或 PowerShell 指令輸出的字元數,最多 128K。超過限制時 Claude Code 會將輸出儲存至檔案,Claude 取得簡短預覽以及路徑。設定它會使 Claude Code 忽略 BASH_MAX_OUTPUT_LENGTH。 |
taskOutputMaxChars | (v2.1.261) Claude 使用 TaskOutput 工具讀取背景任務的輸出時內嵌接收的字元數,最多 128K。對於較長的已完成任務,Claude 接收最新的字元。設定它會使 Claude Code 忽略 TASK_MAX_OUTPUT_LENGTH。 |
{
"wheelScrollAccelerationEnabled": false,
"language": "french",
"footerLinksRegexes": ["https://jira\\.example\\.com/.*"]
}快速參考 (Quick Reference)
最常見的指令 (Most Common Commands)
# 互動式工作階段
claude
# 快速提問
claude -p "how do I..."
# 繼續對話
claude -c
# 處理檔案
cat file.py | claude -p "review this"
# 用於腳本的 JSON 輸出
claude -p --output-format json "query"旗標組合 (Flag Combinations)
| 使用場景 (Use Case) | 指令 (Command) |
|---|---|
| 快速程式碼審查 | cat file | claude -p "review" |
| 結構化輸出 | claude -p --output-format json "query" |
| 安全探索 | claude --permission-mode plan |
| 具備安全性的自主執行 | claude --permission-mode auto |
| CI/CD 整合 | claude -p --max-turns 3 --output-format json |
| 恢復工作 | claude -r "session-name" |
| 自訂模型 | claude --model opus "complex task" |
| 最小模式 | claude --bare "quick query" |
| 預算上限執行 | claude -p --max-budget-usd 2.00 "analyze code" |
疑難排解 (Troubleshooting)
找不到指令 (Command Not Found)
問題: claude: command not found
解決方案:
- 安裝 Claude Code:
npm install -g @anthropic-ai/claude-code - 檢查 PATH 是否包含 npm 全域 bin 目錄
- 嘗試使用完整路徑執行:
npx claude
API 金鑰問題 (API Key Issues)
問題: 驗證失敗 (Authentication failed)
解決方案:
- 設定 API 金鑰:
export ANTHROPIC_API_KEY=your-key - 檢查金鑰是否有效且有足夠的額度
- 驗證要求模型的金鑰權限
找不到工作階段 (Session Not Found)
問題: 無法恢復工作階段
解決方案:
- 列出可用的工作階段以尋找正確的名稱/ID
- 工作階段在閒置一段時間後可能會過期
- 使用
-c繼續最近的工作階段
輸出格式問題 (Output Format Issues)
問題: JSON 輸出格式錯誤 (Malformed)
解決方案:
- 使用
--json-schema強制執行結構 - 在提示詞中加入明確的 JSON 指令
- 使用
--output-format json(而不僅是在提示詞中要求 JSON)
權限被拒絕 (Permission Denied)
問題: 工具執行被封鎖
解決方案:
- 檢查
--permission-mode設定 - 檢視
--allowedTools與--disallowedTools旗標 - 自動化時使用
--dangerously-skip-permissions(請謹慎使用)
額外資源 (Additional Resources)
- 官方 CLI 參考指南 (Official CLI Reference) - 完整的指令參考
- 無頭模式文件 (Headless Mode Documentation) - 自動化執行
- 斜線指令 (Slash Commands) - Claude 內部的自訂捷徑
- 記憶指南 (Memory Guide) - 透過 CLAUDE.md 持久化脈絡
- MCP 協定 (MCP Protocol) - 外部工具整合
- 進階功能 (Advanced Features) - 計劃模式 (Planning Mode)、擴充思考
- 子代理指南 (Subagents Guide) - 委派任務執行
最後更新:2026 年 9 月 6 日 Claude Code 版本:2.1.263 來源:
- https://code.claude.com/docs/en/cli-reference
- https://code.claude.com/docs/en/env-vars
- https://code.claude.com/docs/en/changelog#2-1-174
- https://code.claude.com/docs/en/changelog#2-1-176
- https://code.claude.com/docs/en/changelog
- https://code.claude.com/docs/en/settings
- https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md
- https://code.claude.com/docs/en/troubleshooting
- https://code.claude.com/docs/en/commands
- https://code.claude.com/docs/en/model-config
- https://platform.claude.com/docs/en/about-claude/models/overview
- https://www.anthropic.com/news/claude-opus-4-8
- https://github.com/anthropics/claude-code/releases/tag/v2.1.117
- https://github.com/anthropics/claude-code/releases/tag/v2.1.139
- https://github.com/anthropics/claude-code/releases/tag/v2.1.142
- https://github.com/anthropics/claude-code/releases/tag/v2.1.154
- https://code.claude.com/docs/en/plugins
- https://code.claude.com/docs/en/overview
- https://code.claude.com/docs/en/sub-agents
- https://code.claude.com/docs/en/headless
- https://code.claude.com/docs/en/cli-reference.md
- https://code.claude.com/docs/en/settings.md
- https://code.claude.com/docs/en/settings-reference相容模型:Claude Fable 5, Claude Opus 5, Claude Sonnet 5, Claude Sonnet 4.6, Claude Opus 4.8, Claude Haiku 4.5
