Chương này là tài liệu tra cứu về ba mặt điều khiển Claude Code: slash command (built-in và custom) bên trong session, CLI flag khi khởi động, và headless mode (-p) để chạy Claude Code trong script và CI/CD.
4.1. Slash commands là gì
Slash command điều khiển Claude Code từ bên trong một session. Gõ / để xem mọi command khả dụng, hoặc / theo sau vài ký tự để lọc. Command chỉ được nhận diện khi đứng ở đầu message; phần text theo sau tên command trở thành argument của nó.
- Nếu bạn gửi một command trong lúc Claude đang trả lời, nó được xếp hàng và chạy sau khi turn hiện tại kết thúc. Một số command như
/status,/tasks,/usagechạy ngay lập tức mà không ngắt response. - Autocomplete hoạt động ở bất kỳ vị trí nào trong input, không chỉ ở đầu. Gõ
/tại bất kỳ đâu để xem gợi ý. - Không phải command nào cũng hiện với mọi user. Khả dụng phụ thuộc platform, plan, và environment.
4.2. Built-in slash commands thường dùng
Bảng dưới liệt kê các built-in command hay dùng. Ký hiệu <arg> là argument bắt buộc, [arg] là tùy chọn.
| Command | Mục đích |
|---|---|
/help | Hiển thị trợ giúp và danh sách command |
/init | Khởi tạo project với file CLAUDE.md |
/memory | Sửa file CLAUDE.md, bật/tắt auto-memory |
/clear [name] | Bắt đầu conversation mới với context rỗng (giữ project memory). Alias: /reset, /new |
/compact [instructions] | Giải phóng context bằng cách tóm tắt conversation, kèm focus instruction tùy chọn |
/context [all] | Trực quan hóa mức dùng context dưới dạng lưới màu |
/model [model] | Đổi model và lưu làm default cho session mới |
/effort [level|auto] | Đặt effort level: low, medium, high, xhigh, max, ultracode, auto |
/plan [description] | Vào plan mode trực tiếp từ prompt |
/config [key=value ...] | Mở Settings, hoặc set thẳng: /config theme=dark. Alias: /settings |
/permissions | Quản lý rule allow/ask/deny cho tool. Alias: /allowed-tools |
/mcp [...] | Quản lý kết nối MCP server và OAuth |
/hooks | Xem cấu hình hook cho tool event |
/agents | Nhắc tạo/quản lý subagent (sửa .claude/agents/ hoặc ~/.claude/agents/) |
/skills | Liệt kê skill khả dụng |
/plugin [subcommand] | Quản lý plugin: list, install, enable, disable |
/resume [session] | Resume conversation theo ID/tên, hoặc mở picker. Alias: /continue |
/rewind | Rewind conversation và/hoặc code về checkpoint. Alias: /checkpoint, /undo |
/diff | Mở diff viewer tương tác cho thay đổi chưa commit |
/code-review [level] [--fix] [--comment] [target] | Review diff tìm bug và cleanup |
/review [PR] | Review nhanh một GitHub PR, read-only |
/security-review | Phân tích thay đổi trên branch tìm lỗ hổng bảo mật |
/usage | Hiển thị cost, giới hạn plan, thống kê. Alias: /cost, /stats |
/doctor | Chạy setup checkup, chẩn đoán và có thể sửa lỗi cài đặt. Alias: /checkup |
/export [filename] | Export conversation ra file/clipboard |
/vim | Bật hoặc tắt Vim editing mode |
Lưu ý: một số command trong tài liệu cũ (
/bug,/theme,/login,/logout,/statusline) vẫn tồn tại. Danh sách đầy đủ luôn xem bằng/helphoặc trangcommandstrong docs.
4.3. Custom slash commands
Custom slash command cho phép định nghĩa các prompt hay dùng dưới dạng file Markdown mà Claude Code thực thi. Command được tổ chức theo scope (project hoặc personal) và hỗ trợ namespacing qua cấu trúc thư mục.
Syntax
/<command-name> [arguments]
<command-name> lấy từ tên file Markdown (bỏ đuôi .md).
Command types
Project commands — lưu trong repo, chia sẻ với team. Hiện "(project)" trong /help.
Location: .claude/commands/
# Tạo project command
mkdir -p .claude/commands
echo "Analyze this code for performance issues and suggest optimizations:" > .claude/commands/optimize.md
Personal commands — khả dụng ở mọi project. Hiện "(user)" trong /help.
Location: ~/.claude/commands/
# Tạo personal command
mkdir -p ~/.claude/commands
echo "Review this code for security vulnerabilities:" > ~/.claude/commands/security-review.md
Nếu project command và user command trùng tên, project command được ưu tiên và user command bị bỏ qua âm thầm.
Namespacing
Dùng subdirectory để nhóm command. Subdirectory hiện trong description nhưng không ảnh hưởng tên command.
.claude/commands/frontend/component.mdtạo/componentvới description "(project:frontend)".claude/commands/frontend/test.mdvà.claude/commands/backend/test.mdđều tạo/test, phân biệt qua "(project:frontend)" và "(project:backend)"
Arguments
Dùng placeholder để truyền giá trị động.
$ARGUMENTS bắt toàn bộ argument:
echo 'Fix issue #$ARGUMENTS following our coding standards' > .claude/commands/fix-issue.md
# > /fix-issue 123 high-priority
# $ARGUMENTS thành: "123 high-priority"
$0, $1, ... truy cập từng argument theo vị trí, bắt đầu từ 0:
echo 'Review PR #$0 with priority $1 and assign to $2' > .claude/commands/review-pr.md
# > /review-pr 456 high alice
# $0 = "456", $1 = "high", $2 = "alice"
Dùng positional argument khi cần truy cập argument riêng lẻ ở các phần khác nhau, cung cấp default cho argument thiếu, hoặc dựng command có cấu trúc rõ ràng.
Bash command execution
Thực thi bash command trước khi slash command chạy bằng prefix !. Output được đưa vào context của command. Bạn phải khai báo allowed-tools với tool Bash.
---
allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*)
description: Create a git commit
---
## Context
- Current git status: !`git status`
- Current git diff (staged and unstaged changes): !`git diff HEAD`
- Current branch: !`git branch --show-current`
- Recent commits: !`git log --oneline -10`
## Your task
Based on the above changes, create a single git commit.
File references
Chèn nội dung file vào command bằng prefix @:
# Reference một file cụ thể
Review the implementation in @src/utils/helpers.js
# Reference nhiều file
Compare @src/old-version.js with @src/new-version.js
Thinking mode
Slash command có thể kích hoạt extended thinking bằng cách gồm các extended thinking keyword.
Frontmatter
File command hỗ trợ frontmatter để khai báo metadata.
| Frontmatter | Mục đích | Default |
|---|---|---|
allowed-tools | Danh sách tool command được dùng | Kế thừa từ conversation |
argument-hint | Argument mong đợi, ví dụ add [tagId] | remove [tagId] | list. Hiện khi autocomplete | None |
context | Đặt fork để chạy trong forked sub-agent context với history riêng | Inline (no fork) |
agent | Chọn agent type khi context: fork được đặt | general-purpose |
description | Mô tả ngắn gọn command | Dòng đầu của prompt |
model | Chuỗi model cụ thể | Kế thừa từ conversation |
disable-model-invocation | Ngăn tool Skill gọi command này | false |
hooks | Định nghĩa hook scoped cho lần chạy command này | None |
Ví dụ đầy đủ:
---
allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*)
argument-hint: [message]
description: Create a git commit
model: claude-3-5-haiku-20241022
---
Create a git commit with message: $ARGUMENTS
Ví dụ với positional argument:
---
argument-hint: [pr-number] [priority] [assignee]
description: Review pull request
---
Review PR #$0 with priority $1 and assign to $2.
Focus on security, performance, and code style.
Hooks trong command
Command có thể định nghĩa hook chạy trong lúc thực thi qua field hooks (PreToolUse, PostToolUse, Stop):
---
description: Deploy to staging with validation
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-deploy.sh"
once: true
---
Deploy the current branch to staging environment.
once: true chỉ chạy hook một lần mỗi session. Hook định nghĩa trong command được scoped cho lần chạy đó và tự dọn khi command kết thúc.
Tool Skill — Claude tự gọi command
Tool Skill cho phép Claude chủ động gọi custom slash command và Agent Skill trong conversation. Command muốn được gọi phải có frontmatter description. Phần lớn built-in command như /compact không khả dụng qua tool này; các ngoại lệ hiện có gồm /init, /review và /security-review.
Để khuyến khích Claude dùng, tham chiếu command theo tên (kèm dấu /) trong prompt hoặc CLAUDE.md:
> Run /write-unit-test when you are about to start writing tests.
- Chặn toàn bộ: thêm
Skillvào deny rule qua/permissions. - Chặn một command cụ thể: thêm
disable-model-invocation: truevào frontmatter. - Permission rule:
Skill(commit)(exact match),Skill(review-pr *)(prefix match theo argument). - Character budget mặc định bằng 2% context window, fallback 16.000 ký tự; đổi qua env var
SLASH_COMMAND_TOOL_CHAR_BUDGET.
Plugin và MCP slash commands
- Plugin command: đặt trong thư mục
commands/ở gốc plugin, tự khả dụng khi plugin được cài. Namespaced dạng/plugin-name:command-namekhi cần tránh trùng. - MCP command: server MCP expose prompt thành command, theo pattern
/mcp__<server-name>__<prompt-name> [arguments], ví dụ/mcp__github__pr_review 456.
Slash command vs Agent Skill
| Aspect | Slash Commands | Agent Skills |
|---|---|---|
| Complexity | Prompt đơn giản | Capability phức tạp |
| Structure | 1 file .md | Thư mục SKILL.md + resource |
| Discovery | Invocation tường minh (/command) | Tự động (theo context) |
| Files | Chỉ một file | Nhiều file, script, template |
Dùng slash command cho prompt ngắn, hay dùng, muốn kiểm soát tường minh khi nào chạy. Dùng Skill khi cần workflow nhiều bước, script/utility, hoặc kiến thức trải trên nhiều file.
4.4. CLI reference — khởi động session
CLI commands cơ bản
| Command | Mô tả | Ví dụ |
|---|---|---|
claude | Mở session tương tác | claude |
claude "query" | Session tương tác với prompt khởi đầu | claude "explain this project" |
claude -p "query" | Query qua SDK rồi thoát (headless) | claude -p "explain this function" |
cat file | claude -p "query" | Xử lý nội dung piped | cat logs.txt | claude -p "explain" |
claude -c | Tiếp tục conversation gần nhất ở thư mục hiện tại | claude -c |
claude -c -p "query" | Tiếp tục qua SDK | claude -c -p "Check for type errors" |
claude -r "<session>" "query" | Resume session theo ID/tên | claude -r "auth-refactor" "Finish this PR" |
claude update | Cập nhật lên bản mới nhất | claude update |
claude install [version] | Cài/cài lại native binary | claude install stable |
claude mcp | Cấu hình MCP server | — |
claude doctor | In chẩn đoán cài đặt (read-only) từ terminal | claude doctor |
claude agents | Mở agent view giám sát/điều phối background session | claude agents --json |
claude setup-token | Sinh OAuth token dài hạn cho CI và script | claude setup-token |
Nếu gõ sai subcommand, Claude Code gợi ý bản gần nhất và thoát: claude udpate in Did you mean claude update?.
CLI flags quan trọng
claude --help không liệt kê mọi flag; flag vắng mặt trong --help không có nghĩa là không khả dụng.
| Flag | Mô tả |
|---|---|
--print, -p | In response không vào interactive mode (headless) |
--add-dir | Thêm working directory cho Claude đọc/sửa file |
--model | Đặt model cho session: alias (sonnet, opus, haiku, fable) hoặc tên đầy đủ |
--effort | Đặt effort level: low, medium, high, xhigh, max, ultracode |
--fallback-model | Fallback tự động khi model chính quá tải/không khả dụng (danh sách phân cách bằng dấu phẩy) |
--permission-mode | Bắt đầu ở permission mode: default, acceptEdits, plan, auto, dontAsk, bypassPermissions |
--dangerously-skip-permissions | Bỏ qua permission prompt (= --permission-mode bypassPermissions) |
--allowedTools, --allowed-tools | Tool được chạy không cần hỏi permission |
--disallowedTools, --disallowed-tools | Deny rule; tên tool trần loại tool khỏi context |
--tools | Giới hạn built-in tool khả dụng: "" tắt hết, "default" tất cả, "Bash,Edit,Read" |
--continue, -c | Load conversation gần nhất ở thư mục hiện tại |
--resume, -r | Resume session theo ID/tên hoặc mở picker |
--fork-session | Khi resume, tạo session ID mới thay vì tái dùng ID gốc |
--session-id | Dùng session ID cụ thể (UUID hợp lệ) |
--name, -n | Đặt tên hiển thị cho session |
--append-system-prompt | Thêm text vào cuối default system prompt |
--system-prompt | Thay toàn bộ system prompt bằng text custom |
--agents | Định nghĩa custom subagent qua JSON |
--mcp-config | Load MCP server từ file/chuỗi JSON |
--strict-mcp-config | Chỉ dùng MCP server từ --mcp-config, bỏ mọi cấu hình khác |
--settings | Path tới file settings JSON hoặc chuỗi JSON inline (override cho session) |
--setting-sources | Danh sách nguồn settings load: user, project, local |
--worktree, -w | Chạy trong git worktree cô lập tại <repo>/.claude/worktrees/<name> |
--bg, --background | Chạy session như background agent, trả về ngay (không kết hợp với -p) |
--verbose | Bật verbose logging, hiện output từng turn |
--debug | Bật debug mode, có thể lọc category ("api,mcp") |
--safe-mode | Tắt mọi customization để troubleshoot cấu hình hỏng |
--version, -v | In số version |
System prompt flags
Bốn flag tùy chỉnh system prompt, hoạt động cả interactive lẫn non-interactive:
| Flag | Hành vi |
|---|---|
--system-prompt | Thay toàn bộ default prompt |
--system-prompt-file | Thay bằng nội dung file |
--append-system-prompt | Thêm vào cuối default prompt |
--append-system-prompt-file | Thêm nội dung file vào cuối default prompt |
--system-prompt và --system-prompt-file loại trừ lẫn nhau. Các flag append kết hợp được với flag thay thế. Dùng append khi Claude vẫn là coding assistant nhưng theo thêm rule của bạn; dùng thay thế khi identity/surface khác hẳn Claude Code (thay thế bỏ mọi default prompt gồm cả tool guidance và safety instruction).
4.5. Headless mode (claude -p)
Thêm -p (hoặc --print) vào bất kỳ lệnh claude nào để chạy non-interactive. Mọi CLI option đều dùng được với -p. Đây là cách chạy Claude Code trong script và CI/CD qua Agent SDK.
claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"
Bare mode — khởi động nhanh hơn
Thêm --bare để giảm thời gian khởi động bằng cách bỏ auto-discovery của hook, skill, plugin, MCP server, auto memory, và CLAUDE.md. Hữu ích cho CI và script cần kết quả giống nhau trên mọi máy — chỉ flag bạn truyền tường minh mới có tác dụng.
claude --bare -p "Summarize this file" --allowedTools "Read"
Trong bare mode Claude có Bash, file read, file edit. Truyền context cần thiết qua flag:
| Để load | Dùng |
|---|---|
| System prompt additions | --append-system-prompt, --append-system-prompt-file |
| Settings | --settings <file-or-json> |
| MCP servers | --mcp-config <file-or-json> |
| Custom agents | --agents <json> |
| A plugin | --plugin-dir <path>, --plugin-url <url> |
Bare mode bỏ OAuth và keychain; xác thực Anthropic phải đến từ ANTHROPIC_API_KEY hoặc apiKeyHelper trong JSON của --settings. --bare là mode khuyến nghị cho script/SDK và sẽ thành default của -p trong tương lai.
Pipe dữ liệu qua Claude
Non-interactive mode đọc stdin, nên pipe vào và redirect ra như công cụ CLI bất kỳ:
cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt
Stdin piped bị giới hạn 10MB (từ v2.1.128); vượt cap thì thoát với lỗi rõ ràng. Với input lớn, ghi ra file và tham chiếu path trong prompt.
Output format
Dùng --output-format để kiểm soát cách trả về:
text(default): plain text.json: JSON córesult,session_id, metadata (gồmtotal_cost_usdvà breakdown cost per-model).stream-json: JSON phân tách bằng newline, cho streaming real-time.
claude -p "Summarize this project" --output-format json | jq -r '.result'
Structured output theo schema
Kết hợp --output-format json với --json-schema để nhận output khớp JSON Schema; kết quả nằm ở field structured_output.
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"]}'
Stream responses
Dùng --output-format stream-json với --verbose và --include-partial-messages để nhận token khi được sinh. Mỗi dòng là một JSON event; dòng cuối là message result với text cuối, cost, và session metadata.
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'
Message từ subagent xuất hiện dạng assistant/user với parent_tool_use_id là ID của tool call sinh ra subagent (null với conversation chính). Mặc định chỉ emit block tool_use/tool_result của subagent; thêm --forward-subagent-text để emit cả text và thinking block.
Auto-approve tool
Dùng --allowedTools để Claude dùng tool nhất định không cần hỏi:
claude -p "Run the test suite and fix any failures" \
--allowedTools "Bash,Read,Edit"
--allowedTools dùng permission rule syntax. Dấu * ở cuối bật prefix matching: Bash(git diff *) cho phép mọi lệnh bắt đầu bằng git diff. Khoảng trắng trước * quan trọng — thiếu nó Bash(git diff*) cũng khớp git diff-index.
Thay vì liệt kê từng tool, có thể đặt baseline cho cả session bằng permission mode: dontAsk từ chối mọi thứ ngoài rule permissions.allow (hữu ích cho CI khóa chặt); acceptEdits cho phép ghi file không hỏi và tự duyệt lệnh filesystem thông dụng (mkdir, touch, mv, cp).
claude -p "Apply the lint fixes" --permission-mode acceptEdits
Continue conversations trong -p
# Request đầu
claude -p "Review this codebase for performance issues"
# Tiếp tục conversation gần nhất
claude -p "Now focus on the database queries" --continue
# Bắt session ID để resume đúng conversation
session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
claude -p "Continue that review" --resume "$session_id"
Chạy các lệnh từ cùng thư mục: tra cứu session ID scoped theo thư mục project hiện tại và git worktree của nó.
Dùng slash command trong -p
Skill do user gọi và custom command hoạt động trong -p: gồm /skill-name trong chuỗi prompt và Claude Code expand trước khi chạy. Built-in command chỉ chạy trong terminal (như /login) không khả dụng. Từ v2.1.205, /model, /effort, /fast, /color, /rename nhận value làm argument (ví dụ /model sonnet); đổi setting bằng /config key=value (ví dụ /config thinking=false).
Kiểm soát chi phí và vòng lặp (print mode)
| Flag | Mục đích |
|---|---|
--max-turns | Giới hạn số agentic turn; thoát với lỗi khi chạm giới hạn |
--max-budget-usd | Số tiền tối đa chi cho API call trước khi dừng |
--no-session-persistence | Không lưu session ra disk, không resume được |
Hành vi background task khi thoát
Nếu Claude khởi động background Bash task trong lúc chạy claude -p (ví dụ dev server), shell đó bị kết thúc khoảng 5 giây sau khi Claude trả kết quả cuối và stdin đóng. Background subagent và workflow được miễn grace period vì kết quả của chúng là phần của output cuối; claude -p chờ chúng hoàn tất (mặc định cap 10 phút, chỉnh qua CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS). Dừng bằng SIGTERM thì Claude Code abort turn, kết thúc process tree của Bash, chạy SessionEnd hook, và thoát với code 143.
Ví dụ: Claude làm linter trong build script
Bọc lệnh non-interactive trong script để dùng Claude như linter/reviewer riêng của project:
{
"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.\""
}
}
Pipe diff nghĩa là Claude không cần Bash permission để đọc nó; escape dấu ngoặc kép giữ script chạy được trên Windows.
Xem thêm
content/en/docs/claude-code/slash-commands.md— Slash commands (built-in, custom, plugin, MCP, toolSkill)content/en/docs/claude-code/commands.md— Bảng đầy đủ mọi command với version notecontent/en/docs/claude-code/cli-reference.md— CLI command và flag đầy đủcontent/en/docs/claude-code/headless.md— Chạy Claude Code qua Agent SDK /claude -pcontent/en/docs/claude-code/settings.md— Permission rule syntax và settings precedencecontent/en/docs/claude-code/skills.md— Agent Skills, so sánh với slash commandcontent/en/docs/claude-code/sub-agents.md— Subagent, forked context (context: fork)