跳轉到主要內容
使用自訂狀態行自訂 Claude Code,該狀態行會顯示在 Claude Code 介面的底部,類似於 Oh-my-zsh 等 shell 中的終端提示符 (PS1) 的運作方式。

建立自訂狀態行

您可以:
  • 執行 /statusline 以要求 Claude Code 協助您設定自訂狀態行。預設情況下,它會嘗試重現您終端的提示符,但您可以向 Claude Code 提供有關您想要的行為的其他指示,例如 /statusline show the model name in orange
  • 直接將 statusLine 命令新增到您的 .claude/settings.json
{
  "statusLine": {
    "type": "command",
    "command": "~/.claude/statusline.sh",
    "padding": 0 // 選用:設定為 0 以讓狀態行延伸至邊緣
  }
}

運作方式

  • 狀態行會在對話訊息更新時更新
  • 更新最多每 300 毫秒執行一次
  • 您命令的 stdout 的第一行會成為狀態行文字
  • 支援 ANSI 色碼以設定狀態行的樣式
  • Claude Code 會透過 stdin 以 JSON 格式將有關目前工作階段的上下文資訊 (模型、目錄等) 傳遞給您的指令碼

JSON 輸入結構

您的狀態行命令會透過 stdin 以 JSON 格式接收結構化資料:
{
  "hook_event_name": "Status",
  "session_id": "abc123...",
  "transcript_path": "/path/to/transcript.json",
  "cwd": "/current/working/directory",
  "model": {
    "id": "claude-opus-4-1",
    "display_name": "Opus"
  },
  "workspace": {
    "current_dir": "/current/working/directory",
    "project_dir": "/original/project/directory"
  },
  "version": "1.0.80",
  "output_style": {
    "name": "default"
  },
  "cost": {
    "total_cost_usd": 0.01234,
    "total_duration_ms": 45000,
    "total_api_duration_ms": 2300,
    "total_lines_added": 156,
    "total_lines_removed": 23
  },
  "context_window": {
    "total_input_tokens": 15234,
    "total_output_tokens": 4521,
    "context_window_size": 200000,
    "current_usage": {
      "input_tokens": 8500,
      "output_tokens": 1200,
      "cache_creation_input_tokens": 5000,
      "cache_read_input_tokens": 2000
    }
  }
}

範例指令碼

簡單狀態行

#!/bin/bash
# 從 stdin 讀取 JSON 輸入
input=$(cat)

# 使用 jq 提取值
MODEL_DISPLAY=$(echo "$input" | jq -r '.model.display_name')
CURRENT_DIR=$(echo "$input" | jq -r '.workspace.current_dir')

echo "[$MODEL_DISPLAY] 📁 ${CURRENT_DIR##*/}"

Git 感知狀態行

#!/bin/bash
# 從 stdin 讀取 JSON 輸入
input=$(cat)

# 使用 jq 提取值
MODEL_DISPLAY=$(echo "$input" | jq -r '.model.display_name')
CURRENT_DIR=$(echo "$input" | jq -r '.workspace.current_dir')

# 如果在 git 儲存庫中,顯示 git 分支
GIT_BRANCH=""
if git rev-parse --git-dir > /dev/null 2>&1; then
    BRANCH=$(git branch --show-current 2>/dev/null)
    if [ -n "$BRANCH" ]; then
        GIT_BRANCH=" | 🌿 $BRANCH"
    fi
fi

echo "[$MODEL_DISPLAY] 📁 ${CURRENT_DIR##*/}$GIT_BRANCH"

Python 範例

#!/usr/bin/env python3
import json
import sys
import os

# 從 stdin 讀取 JSON
data = json.load(sys.stdin)

# 提取值
model = data['model']['display_name']
current_dir = os.path.basename(data['workspace']['current_dir'])

# 檢查 git 分支
git_branch = ""
if os.path.exists('.git'):
    try:
        with open('.git/HEAD', 'r') as f:
            ref = f.read().strip()
            if ref.startswith('ref: refs/heads/'):
                git_branch = f" | 🌿 {ref.replace('ref: refs/heads/', '')}"
    except:
        pass

print(f"[{model}] 📁 {current_dir}{git_branch}")

Node.js 範例

#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

// 從 stdin 讀取 JSON
let input = '';
process.stdin.on('data', chunk => input += chunk);
process.stdin.on('end', () => {
    const data = JSON.parse(input);
    
    // 提取值
    const model = data.model.display_name;
    const currentDir = path.basename(data.workspace.current_dir);
    
    // 檢查 git 分支
    let gitBranch = '';
    try {
        const headContent = fs.readFileSync('.git/HEAD', 'utf8').trim();
        if (headContent.startsWith('ref: refs/heads/')) {
            gitBranch = ` | 🌿 ${headContent.replace('ref: refs/heads/', '')}`;
        }
    } catch (e) {
        // 不是 git 儲存庫或無法讀取 HEAD
    }
    
    console.log(`[${model}] 📁 ${currentDir}${gitBranch}`);
});

協助函數方法

對於更複雜的 bash 指令碼,您可以建立協助函數:
#!/bin/bash
# 一次讀取 JSON 輸入
input=$(cat)

# 常見提取的協助函數
get_model_name() { echo "$input" | jq -r '.model.display_name'; }
get_current_dir() { echo "$input" | jq -r '.workspace.current_dir'; }
get_project_dir() { echo "$input" | jq -r '.workspace.project_dir'; }
get_version() { echo "$input" | jq -r '.version'; }
get_cost() { echo "$input" | jq -r '.cost.total_cost_usd'; }
get_duration() { echo "$input" | jq -r '.cost.total_duration_ms'; }
get_lines_added() { echo "$input" | jq -r '.cost.total_lines_added'; }
get_lines_removed() { echo "$input" | jq -r '.cost.total_lines_removed'; }
get_input_tokens() { echo "$input" | jq -r '.context_window.total_input_tokens'; }
get_output_tokens() { echo "$input" | jq -r '.context_window.total_output_tokens'; }
get_context_window_size() { echo "$input" | jq -r '.context_window.context_window_size'; }

# 使用協助函數
MODEL=$(get_model_name)
DIR=$(get_current_dir)
echo "[$MODEL] 📁 ${DIR##*/}"

上下文視窗使用量

顯示已消耗的上下文視窗百分比。context_window 物件包含:
  • total_input_tokens / total_output_tokens:整個工作階段中的累積總計
  • current_usage:上次 API 呼叫的目前上下文視窗使用量 (如果還沒有訊息,可能為 null)
    • input_tokens:目前上下文中的輸入權杖
    • output_tokens:產生的輸出權杖
    • cache_creation_input_tokens:寫入快取的權杖
    • cache_read_input_tokens:從快取讀取的權杖
為了獲得準確的上下文百分比,請使用 current_usage,它反映實際的上下文視窗狀態:
#!/bin/bash
input=$(cat)

MODEL=$(echo "$input" | jq -r '.model.display_name')
CONTEXT_SIZE=$(echo "$input" | jq -r '.context_window.context_window_size')
USAGE=$(echo "$input" | jq '.context_window.current_usage')

if [ "$USAGE" != "null" ]; then
    # 從 current_usage 欄位計算目前上下文
    CURRENT_TOKENS=$(echo "$USAGE" | jq '.input_tokens + .cache_creation_input_tokens + .cache_read_input_tokens')
    PERCENT_USED=$((CURRENT_TOKENS * 100 / CONTEXT_SIZE))
    echo "[$MODEL] Context: ${PERCENT_USED}%"
else
    echo "[$MODEL] Context: 0%"
fi

提示

  • 保持狀態行簡潔 - 應該適合一行
  • 使用表情符號 (如果您的終端支援) 和顏色使資訊易於掃描
  • 在 Bash 中使用 jq 進行 JSON 解析 (請參閱上面的範例)
  • 透過使用模擬 JSON 輸入手動執行指令碼來測試它:echo '{"model":{"display_name":"Test"},"workspace":{"current_dir":"/test"}}' | ./statusline.sh
  • 如果需要,考慮快取昂貴的操作 (如 git 狀態)

疑難排解

  • 如果您的狀態行沒有出現,請檢查您的指令碼是否可執行 (chmod +x)
  • 確保您的指令碼輸出到 stdout (而不是 stderr)