> ## Documentation Index
> Fetch the complete documentation index at: https://felimet-hub.jmcores.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 04-3 Command（slash command）：是什麼、用途、製作

> slash command 把一段常用 prompt 或流程綁成 /name 一鍵叫用。本單元講 command 的格式、製作方式、$ARGUMENTS 參數注入，以及和 Skill 的分工判準。

export const LearnerPrimer = ({items = [], lang = "zh"}) => {
  const t = lang === "en" ? {
    title: "Before this unit, be honest with yourself",
    sub: "If you can't answer these, that gap is exactly what this unit closes."
  } : {
    title: "讀這個單元前，先誠實面對",
    sub: "這幾題答不出來，正是這個單元要替你補的洞。"
  };
  const css = `
  .lp-root{--lp-bg:#FAF7F1;--lp-surface:rgba(191,117,81,0.05);--lp-border:rgba(0,0,0,0.09);--lp-edge:rgba(191,117,81,0.42);--lp-text:#2b2722;--lp-dim:#6f6a62;--lp-accent:#bf7551;border:1px solid var(--lp-border);border-left:3px solid var(--lp-edge);border-radius:13px;background:var(--lp-bg);color:var(--lp-text);overflow:hidden;margin:1.25rem 0;}
  .dark .lp-root{--lp-bg:#1b1a18;--lp-surface:rgba(207,138,104,0.07);--lp-border:rgba(255,255,255,0.08);--lp-edge:rgba(207,138,104,0.5);--lp-text:#e7e3da;--lp-dim:#a8a299;--lp-accent:#cf8a68;}
  .lp-head{display:flex;align-items:center;gap:9px;padding:13px 18px 11px;border-bottom:1px solid var(--lp-border);background:var(--lp-surface);}
  .lp-ic{color:var(--lp-accent);flex-shrink:0;}
  .lp-htx{display:flex;flex-direction:column;gap:1px;min-width:0;}
  .lp-title{font-size:14px;font-weight:650;line-height:1.3;letter-spacing:.01em;}
  .lp-sub{font-size:12px;color:var(--lp-dim);line-height:1.4;}
  .lp-list{list-style:none;margin:0;padding:10px 18px 14px;display:flex;flex-direction:column;gap:0;}
  .lp-item{display:flex;align-items:baseline;gap:11px;padding:7px 0;font-size:14px;line-height:1.6;border-top:1px solid var(--lp-border);}
  .lp-item:first-child{border-top:none;}
  .lp-mark{flex-shrink:0;color:var(--lp-accent);font-size:13px;font-weight:700;line-height:1.55;font-variant-numeric:tabular-nums;opacity:.85;}
  .lp-q{flex:1 1 0;min-width:0;color:var(--lp-text);}
  @media (max-width:620px){.lp-head{padding:12px 14px 10px;}.lp-list{padding:8px 14px 12px;}}
  `;
  return <div className="lp-root">
      <style>{css}</style>
      <div className="lp-head">
        <svg className="lp-ic" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10" /><circle cx="12" cy="12" r="6" /><circle cx="12" cy="12" r="2" /></svg>
        <span className="lp-htx">
          <span className="lp-title">{t.title}</span>
          <span className="lp-sub">{t.sub}</span>
        </span>
      </div>
      <ul className="lp-list">
        {items.map((q, i) => <li className="lp-item" key={i}>
            <span className="lp-mark">{String(i + 1).padStart(2, "0")}</span>
            <span className="lp-q">{q}</span>
          </li>)}
      </ul>
    </div>;
};

<LearnerPrimer
  lang="zh"
  items={[
"command 你不打，模型也不會打。",
"帶副作用的工作流，預設都加 disable-model-invocation。",
"$ARGUMENTS 是省重複。",
"command 是主動，Skill 是自動。",
"描述寫太模糊，三天後你自己也看不懂這 command 幹嘛。",
"你讓 command 帶敏感資訊，commit 進公開 repo 等於主動外洩。",
"部署前不切 disable-model-invocation，模型看「該 deploy 了」就自己跑。",
]}
/>

<Info>
  **這個單元解決什麼問題**

  slash command 把一段常用 prompt 或流程綁成 `/name` 一鍵叫用。它和 Skill 的關鍵差別是：command 由你**主動觸發**，Skill 由模型**自動判斷**是否叫用。本單元講 command 的格式、製作方式、`$ARGUMENTS` 參數注入，以及和 Skill 的分工判準。
</Info>

## 學習目標

* [ ] 說出 command（主動觸發）與 Skill（模型自動叫用）的差別與分工。
* [ ] 在 `.claude/commands/` 或 `~/.claude/commands/` 下建立自訂 command 檔。
* [ ] 用 `$ARGUMENTS`、`$0`、`$1` 等語法接收參數，讓 command 具備動態能力。
* [ ] 用 `disable-model-invocation: true` 限制 Claude 自動叫用特定 command。
* [ ] 判斷一個需求該做成 command 還是 Skill，並說出判準。

***

## 1. command 是什麼

slash command 是你在 Claude Code session 開頭打 `/name` 觸發的封裝 prompt。它不依賴模型主動識別意圖，**你打什麼就跑什麼**（截至 2026-06，依官方 commands 章節 \[1]）。

三個關鍵特性：

1. **主動觸發**：你不打，Claude 也不會建議打。決定權完全在你。
2. **可重用**：寫一次，之後每次都一樣的叫用方式。
3. **可版控**：放在 `.claude/commands/` 內可進 Git，團隊共享。

<Tip>
  **command 與一般 prompt 的差異**

  一段 prompt 你可以重複貼，但每次要自己手剪參數、調整措詞。command 把這件事打包：你只需要打 `/<name> <args>`，後面邏輯一致。這個「一致性」在固定輸出格式（commit message、PR 摘要、changelog）或反覆跑的檢查流程上特別值。
</Tip>

## 2. 與 Skill 的差別：主動 vs 自動

`.claude/commands/<name>.md` 與 Skill（`SKILL.md`）在 Claude Code 裡**現在已合併為同一套底層機制** \[2]。但兩者觸發時機不同：

| 維度    | Command                                                       | Skill                                                                 |
| ----- | ------------------------------------------------------------- | --------------------------------------------------------------------- |
| 觸發方式  | 使用者主動打 `/name`                                                | 模型依 `description` 語意判斷叫用                                              |
| 預設可見性 | `/` 選單顯示，使用者輸入                                                | 模型可見，使用者也可打 `/name`                                                   |
| 寫在哪裡  | `.claude/commands/<name>.md` 或 `~/.claude/commands/<name>.md` | `.claude/skills/<name>/SKILL.md` 或 `~/.claude/skills/<name>/SKILL.md` |
| 同名衝突  | 若 skill 與 command 同名，skill 優先 \[2]                            | 同左                                                                    |
| 適合場合  | 「我知道現在要做 X」                                                   | 「讓模型判斷什麼時候做 X」                                                        |

簡化版決策：

* **確定性高、流程固定** → command。
* **有副作用、你不希望模型自己決定何時跑**（deploy、發送訊息、commit）→ command + `disable-model-invocation: true`。
* **依使用者意圖判斷才合適**（code review、文件搜尋、refactor 建議）→ Skill。

<Warning>
  **帶副作用的工作流預設用 command**

  部署、推送、發送 Slack、寫入外部系統；任何「做了就難以撤回」的事，預設用 command + `disable-model-invocation: true`。你不需要 Claude 因為「看起來該發」就自己發。
</Warning>

## 3. 製作：檔案位置與基本結構

放路徑（截至 2026-06）：

| 位置                             | 適用範圍            |
| ------------------------------ | --------------- |
| `~/.claude/commands/<name>.md` | 所有專案通用          |
| `./.claude/commands/<name>.md` | 當前專案，透過版控共享給團隊  |
| `<plugin>/commands/<name>.md`  | 在已啟用 plugin 內可用 |

command 檔的命名就是 `/` 後面要打的字：`.claude/commands/deploy.md` 對應 `/deploy`，`.claude/commands/fix-issue.md` 對應 `/fix-issue`。

### 3.1 最簡形式

```markdown theme={null}
You are helping me write a commit message for the current changes. Use the project's existing commit style (Conventional Commits). Output only the commit message, no preamble.
```

打 `/commit` 觸發後，這段就會被注入 Claude 當下對話，Claude 用它產生 commit message。

### 3.2 用 frontmatter 設定行為

```markdown theme={null}
---
description: Generate a commit message for staged changes
argument-hint: [optional context]
allowed-tools: Bash(git status *) Bash(git diff *) Bash(git log *)
model: sonnet
---

## Staged changes
!`git diff --cached`

## Recent commit style
!`git log --oneline -10`

## Task
Write a Conventional Commits message for the staged changes above.
$ARGUMENTS
```

幾個常用 frontmatter 欄位（截至 2026-06，依官方 Skills 與 commands 章節 \[1, 2]）：

| 欄位                               | 用途                             |
| -------------------------------- | ------------------------------ |
| `description`                    | 在 `/` 選單顯示、Claude 判斷語意時的提示     |
| `argument-hint`                  | 自動完成時的提示文字，例如 `[issue-number]` |
| `allowed-tools`                  | 列出 command 啟用時不需要額外確認的工具       |
| `model`                          | 指定使用模型，預設繼承當前 session          |
| `disable-model-invocation: true` | 禁止 Claude 自動叫用此 command        |
| `user-invocable: false`          | 從 `/` 選單隱藏，只讓模型叫用              |

<Note>
  **為什麼要 `disable-model-invocation: true`**

  假設你寫了 `/deploy` command。如果不限制，模型可能在對話中看到「這段程式碼看起來該部署了」就自己叫用 `/deploy`，然後跑了部署；你可能還在 review。設了 `disable-model-invocation: true` 之後，這個 command 只在你明確打 `/deploy` 時才會跑，模型完全看不到它。對 deploy、send、push 這類**有副作用**的工作流，預設都該加。
</Note>

## 4. 參數注入：`$ARGUMENTS` 與索引語法

command 觸發時，你打 `/name 後面這些字` 會被注入到 command 內容中。

<Steps>
  <Step title="最簡單的接收方式：$ARGUMENTS">
    用 `$ARGUMENTS` 接收你在 `/name` 後面打的所有文字：

    ```markdown theme={null}
    ---
    description: Fix a GitHub issue by number
    ---

    Fix GitHub issue $ARGUMENTS following our coding standards.
    1. Read the issue description
    2. Understand the requirements
    3. Implement the fix
    4. Write tests
    5. Create a commit
    ```

    打 `/fix-issue 123` 時，`$ARGUMENTS` 被替換為 `123`，Claude 收到的是「Fix GitHub issue 123 following our coding standards. ...」\[2]。

    如果 command 內容裡沒有 `$ARGUMENTS`，Claude Code 會把參數以 `ARGUMENTS: <你的輸入>` 形式附加在 command 內容尾端，Claude 還是看得到 \[2]。
  </Step>

  <Step title="位置索引：$0、$1、$2">
    需要把多個參數拆開處理時，用 `$0`、`$1`、`$2` 或 `$ARGUMENTS[0]` 等：

    ```markdown theme={null}
    ---
    description: Migrate a component from one framework to another
    ---

    Migrate the $0 component from $1 to $2.
    Preserve all existing behavior and tests.
    ```

    打 `/migrate-component SearchBar React Vue` 時，`$0` 為 `SearchBar`，`$1` 為 `React`，`$2` 為 `Vue`。

    多字參數要用引號包起來：`/migrate-component "Search Bar" React "Vue 3"`。
  </Step>

  <Step title="具名參數">
    frontmatter 設 `arguments` 後，內容裡可以用名字取：

    ```yaml theme={null}
    ---
    description: Create a commit with branch and issue context
    arguments:
      - branch
      - issue
    ---
    ```

    ```markdown theme={null}
    Create a commit on branch $branch referencing issue $issue.
    ```

    打 `/commit feature-x 456` 時，`$branch` 為 `feature-x`、`$issue` 為 `456` \[2]。
  </Step>
</Steps>

### 4.1 其他可用變數

| 變數                     | 用途                                                        |
| ---------------------- | --------------------------------------------------------- |
| `${CLAUDE_SESSION_ID}` | 當前 session ID，用於日誌或 session 特定檔名                          |
| `${CLAUDE_SKILL_DIR}`  | command/skill 所在目錄，用於引用同目錄腳本                              |
| `${CLAUDE_EFFORT}`     | 當前 effort 等級（`low` / `medium` / `high` / `xhigh` / `max`） |

## 5. 動態 context 注入：`` !`command` ``

command 內容裡可以用 `` !`shell command` `` 在**送進 Claude 之前**先執行 shell 指令，把輸出嵌入內容 \[2]：

```markdown theme={null}
## Current changes
!`git diff HEAD`

## Status
!`git status --short`
```

當 command 被叫用時，Claude Code 依序執行每個 `` !`cmd` ``，把輸出取代進去，**然後才把整段內容當作 prompt 交給 Claude**。對 Claude 來說，它看到的是已經包含 git diff 結果的純文字。

多行指令用 fenced code block 形式：

````markdown theme={null}
## Environment
```!
node --version
npm --version
git status --short
```
````

<Warning>
  **動態注入的兩個陷阱**

  1. **執行環境就是你的 shell**。你打 `/deploy` 時，command 內的 `` !`cmd` `` 是用你的本機 shell 執行的（macOS/Linux 預設 `bash`，Windows 預設 PowerShell 可切換 \[2]）。敏感操作別寫在 command 裡。
  2. **禁用設定**：組織可在 `settings.json` 設 `"disableSkillShellExecution": true`，把所有動態注入替換為 `[shell command execution disabled by policy]`。寫公開 repo 的 command 時不要依賴這個機制跑關鍵步驟。
</Warning>

## 6. 工具對照

| 概念            | Anthropic Claude（主範本）                                       | OpenAI Codex                             | GitHub Copilot                                      | Cursor                              |
| ------------- | ----------------------------------------------------------- | ---------------------------------------- | --------------------------------------------------- | ----------------------------------- |
| 自訂 command 位置 | `.claude/commands/<name>.md`、`~/.claude/commands/<name>.md` | `config.toml` 設定（路徑以 OpenAI 當前文件為準）      | `.github/prompts/<name>.prompt.md`（prompt files 機制） | `.cursor/commands/<name>.md`        |
| 參數注入語法        | `$ARGUMENTS`、`$0`、`$1`、具名變數                                 | 不適用一般 `ARGUMENTS` 語法                     | frontmatter 結構化欄位                                   | `$ARGUMENTS` 風格變數                   |
| 全域 vs 專案作用域   | `~/.claude/commands/` vs `.claude/commands/`                | `~/.codex/prompts/` vs `.codex/prompts/` | 全域與專案分檔                                             | 全域 User Rules + 專案 `.cursor/rules/` |
| 觸發方式          | 使用者主動輸入 `/name`                                             | 使用者主動輸入                                  | 使用者主動輸入                                             | 使用者主動輸入                             |
| 防止模型自動叫用      | `disable-model-invocation: true`                            | （機制差異大）                                  | （機制差異大）                                             | （機制差異大）                             |

<Note>
  **命名澄清**

  Claude Code 的 command 與 skill 為同一底層機制：截至 2026-06 兩者已合併，`.claude/commands/<name>.md` 與 `.claude/skills/<name>/SKILL.md` 都能產生 `/name` \[2]。差別在前者放單一檔、後者放目錄（含 references/ 與 scripts/，見 [04-4 Skill](/code-agent/customization/skills)）。本單元講的是兩者共通的「使用者主動觸發」這一面。OpenAI Codex、GitHub Copilot、Cursor 各有「prompt file」或「prompt template」概念，但路徑與機制差異大；通用寫法是「prompt file 支援 `$ARGUMENTS` 風格變數」，細節以各家當前文件為準。
</Note>

## 7. 動手做

<Note>
  **30 分鐘練習**

  1. **寫一個 `/commit` command**：用 frontmatter 帶 `disable-model-invocation: true` 與 `allowed-tools: Bash(git *)`；內容用 `` !`git diff --cached` `` 與 `` !`git log --oneline -10` `` 取得 staged diff 與最近風格，請 Claude 依 Conventional Commits 格式輸出 commit message。
  2. **建一個全域 command**：`~/.claude/commands/weekly-review.md`，用 `$ARGUMENTS` 接收你想 focus 的主題；啟動新專案 session 測試 `/weekly-review` 可跨專案叫用。
  3. **測試防誤觸**：寫一個 `/deploy-prod` command，故意**不**設 `disable-model-invocation`；在對話中提到「看起來該 deploy 了」觀察 Claude 是否會自己叫用。然後加上 `disable-model-invocation: true`，重複同一句話，確認這次 Claude 不會自己跑。
</Note>

## 8. 常見誤區

<Warning>
  **反模式清單**

  * **把所有流程都做成 command**：使用者主動觸發過多，會讓工作流摩擦增加。該讓模型自己判斷的場合（code review、文件搜尋）改用 Skill。
  * **`description` 寫太模糊**：自己過三天就忘了這個 command 是做什麼用的。具體描述觸發時機與產出格式，別只寫「幫我做 X」。
  * **沒設 `disable-model-invocation` 就寫 deploy/push/send**：模型可能在你還沒確認時自己跑，產生不可逆副作用。
  * **把含敏感資訊的 command 檔 commit 進公開 repo**：command 內容進版控，API key、絕對路徑、內部 URL 都會外洩。
  * **動態注入依賴未驗證狀態**：command 裡寫 `` !`./scripts/deploy.sh` `` 而該腳本權限或內容不固定，重現性就沒了。需要確定性的部署流程應改用 Hook（見 [04-6 Hooks](/code-agent/customization/hooks)）或獨立 CI 步驟。
</Warning>

## 自我檢核

<Check>
  **通過本單元的標準**

  1. 你能說出 command 與 Skill 的根本差別嗎？（觸發主體不同）
  2. 你能在五分鐘內寫出一個能用 `$ARGUMENTS` 接收參數的 command 嗎？
  3. 你能判斷哪些 command 該加 `disable-model-invocation: true` 嗎？
  4. 你手邊有沒有一個每週重複打三次以上的 prompt？它該做成 command 還是 Skill？說出你的判準。
</Check>

## 來源與延伸閱讀

事實主張依官方文件，快變動項標註截至 2026-05。

<div className="references">
  * \[1] Anthropic, "Commands," code.claude.com, 2026. \[Online]. Available: [https://code.claude.com/docs/en/commands](https://code.claude.com/docs/en/commands) （截至 2026-06；含內建與自訂 command）
  * \[2] Anthropic, "Extend Claude with skills," code.claude.com, 2026. \[Online]. Available: [https://code.claude.com/docs/en/skills](https://code.claude.com/docs/en/skills) （截至 2026-06；含 command 與 skill 合併機制、`$ARGUMENTS` 與 frontmatter 完整參考）
  * \[3] Anthropic, "How Claude remembers your project," code.claude.com, 2026. \[Online]. Available: [https://code.claude.com/docs/en/memory](https://code.claude.com/docs/en/memory) （截至 2026-06；`CLAUDE.md` 與 rules 模組化）
</div>

* `CLAUDE.md` 與自動記憶見 [04-1 CLAUDE.md 與記憶檔](/code-agent/customization/claude-md-memory)。
* 規則檔 path-scoped 機制見 [04-2 rules](/code-agent/customization/rules)。
* Skill 進階（references/、scripts/、漸進式揭露）見 [04-4 Skill](/code-agent/customization/skills)。
* Hook 強制執行見 [04-6 Hooks](/code-agent/customization/hooks)。
