làm tíai?GitHub ↗
CHƯƠNG 04 / 16

Slash commands và CLI

Dùng lệnh dựng sẵn, custom commands và chế độ headless cho công việc lặp lại.

15 phút đọc

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, /usage chạ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.

CommandMục đích
/helpHiển thị trợ giúp và danh sách command
/initKhởi tạo project với file CLAUDE.md
/memorySử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
/permissionsQuản lý rule allow/ask/deny cho tool. Alias: /allowed-tools
/mcp [...]Quản lý kết nối MCP server và OAuth
/hooksXem cấu hình hook cho tool event
/agentsNhắc tạo/quản lý subagent (sửa .claude/agents/ hoặc ~/.claude/agents/)
/skillsLiệ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
/rewindRewind conversation và/hoặc code về checkpoint. Alias: /checkpoint, /undo
/diffMở 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-reviewPhân tích thay đổi trên branch tìm lỗ hổng bảo mật
/usageHiển thị cost, giới hạn plan, thống kê. Alias: /cost, /stats
/doctorChạ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
/vimBậ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 /help hoặc trang commands trong 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.md tạo /component với description "(project:frontend)"
  • .claude/commands/frontend/test.md.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.

FrontmatterMục đíchDefault
allowed-toolsDanh sách tool command được dùngKế thừa từ conversation
argument-hintArgument mong đợi, ví dụ add [tagId] | remove [tagId] | list. Hiện khi autocompleteNone
contextĐặt fork để chạy trong forked sub-agent context với history riêngInline (no fork)
agentChọn agent type khi context: fork được đặtgeneral-purpose
descriptionMô tả ngắn gọn commandDòng đầu của prompt
modelChuỗi model cụ thểKế thừa từ conversation
disable-model-invocationNgăn tool Skill gọi command nàyfalse
hooksĐịnh nghĩa hook scoped cho lần chạy command nàyNone

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/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 Skill vào deny rule qua /permissions.
  • Chặn một command cụ thể: thêm disable-model-invocation: true và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-name khi 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

AspectSlash CommandsAgent Skills
ComplexityPrompt đơn giảnCapability phức tạp
Structure1 file .mdThư mục SKILL.md + resource
DiscoveryInvocation tường minh (/command)Tự động (theo context)
FilesChỉ một fileNhiề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

CommandMô tảVí dụ
claudeMở session tương tácclaude
claude "query"Session tương tác với prompt khởi đầuclaude "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 pipedcat logs.txt | claude -p "explain"
claude -cTiếp tục conversation gần nhất ở thư mục hiện tạiclaude -c
claude -c -p "query"Tiếp tục qua SDKclaude -c -p "Check for type errors"
claude -r "<session>" "query"Resume session theo ID/tênclaude -r "auth-refactor" "Finish this PR"
claude updateCập nhật lên bản mới nhấtclaude update
claude install [version]Cài/cài lại native binaryclaude install stable
claude mcpCấu hình MCP server
claude doctorIn chẩn đoán cài đặt (read-only) từ terminalclaude doctor
claude agentsMở agent view giám sát/điều phối background sessionclaude agents --json
claude setup-tokenSinh OAuth token dài hạn cho CI và scriptclaude 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.

FlagMô tả
--print, -pIn response không vào interactive mode (headless)
--add-dirThê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-modelFallback 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-modeBắt đầu ở permission mode: default, acceptEdits, plan, auto, dontAsk, bypassPermissions
--dangerously-skip-permissionsBỏ qua permission prompt (= --permission-mode bypassPermissions)
--allowedTools, --allowed-toolsTool được chạy không cần hỏi permission
--disallowedTools, --disallowed-toolsDeny rule; tên tool trần loại tool khỏi context
--toolsGiới hạn built-in tool khả dụng: "" tắt hết, "default" tất cả, "Bash,Edit,Read"
--continue, -cLoad conversation gần nhất ở thư mục hiện tại
--resume, -rResume session theo ID/tên hoặc mở picker
--fork-sessionKhi resume, tạo session ID mới thay vì tái dùng ID gốc
--session-idDùng session ID cụ thể (UUID hợp lệ)
--name, -nĐặt tên hiển thị cho session
--append-system-promptThêm text vào cuối default system prompt
--system-promptThay toàn bộ system prompt bằng text custom
--agentsĐịnh nghĩa custom subagent qua JSON
--mcp-configLoad MCP server từ file/chuỗi JSON
--strict-mcp-configChỉ dùng MCP server từ --mcp-config, bỏ mọi cấu hình khác
--settingsPath tới file settings JSON hoặc chuỗi JSON inline (override cho session)
--setting-sourcesDanh sách nguồn settings load: user, project, local
--worktree, -wChạy trong git worktree cô lập tại <repo>/.claude/worktrees/<name>
--bg, --backgroundChạy session như background agent, trả về ngay (không kết hợp với -p)
--verboseBật verbose logging, hiện output từng turn
--debugBật debug mode, có thể lọc category ("api,mcp")
--safe-modeTắt mọi customization để troubleshoot cấu hình hỏng
--version, -vIn số version

System prompt flags

Bốn flag tùy chỉnh system prompt, hoạt động cả interactive lẫn non-interactive:

FlagHành vi
--system-promptThay toàn bộ default prompt
--system-prompt-fileThay bằng nội dung file
--append-system-promptThêm vào cuối default prompt
--append-system-prompt-fileThêm nội dung file vào cuối default prompt

--system-prompt--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:

Để loadDù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ồm total_cost_usd và 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--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)

FlagMục đích
--max-turnsGiới hạn số agentic turn; thoát với lỗi khi chạm giới hạn
--max-budget-usdSố tiền tối đa chi cho API call trước khi dừng
--no-session-persistenceKhô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, tool Skill)
  • content/en/docs/claude-code/commands.md — Bảng đầy đủ mọi command với version note
  • content/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 -p
  • content/en/docs/claude-code/settings.md — Permission rule syntax và settings precedence
  • content/en/docs/claude-code/skills.md — Agent Skills, so sánh với slash command
  • content/en/docs/claude-code/sub-agents.md — Subagent, forked context (context: fork)
Nguồn của chương

Tài liệu chính thức duy nhất từ Anthropic.

Claude Code docs
Trở về mục lục