Skip to main content

Claude Code Statusline Setup: Working Script and Troubleshooting

Use /statusline for a quick personal setup, or connect a small Python script for a configuration you can maintain. Test it with mock JSON before troubleshooting settings, update triggers, or Windows paths.

LaoZhang AI TeamPublishedUpdated 12 min read
On this page
Conceptual Claude Code statusline setup through the slash command or a manual script, with synthetic model, directory, context and cost fields

To configure a Claude Code statusline, run /statusline inside Claude Code and describe the fields you want, or add a statusLine command to your settings. The command receives JSON on stdin and prints the visible text to stdout. A small manual script is useful when you want to understand exactly what runs and keep it under version control.

Start with model, directory, Git branch, context usage, and an estimated session cost. The Python example below includes a mock test and handles missing values without turning them into zero. It also shows a five-hour usage percentage when Claude Code supplies a valid, unexpired window.

Choose /statusline, a manual script, or a formatter

What you wantStart hereWhat to check before keeping it
A quick personal statusline/statuslineRead the generated script and confirm its output
A small, maintainable implementationManual statusLine commandRun the script with mock stdin first
Consistent behavior for a teamA reviewed repo script and shared project settingsAgree on runtimes, paths, and any local commands
Themes, configurable widgets, or multiple layoutsAn optional formatter such as ccstatuslineCheck its dependencies and the data sources of the widgets you enable

For the first route, enter this inside Claude Code:

/statusline Show the model, current directory, Git branch, context used percentage, and estimated session cost. Keep it short and show unknown values clearly.

The official statusline guide describes how this command generates a script and updates your settings. The generated result is still a local program: inspect it before committing it or using it as a team default. A personal absolute path will not work on every teammate's machine.

Manual setup: a complete Python statusline example

This example requires Python 3. Git is optional; when Git is unavailable or the supplied directory cannot be queried, the branch segment becomes git:-. Python's standard library is sufficient, so there is no package installation step for the script.

Create a directory for your personal script:

bash
mkdir -p "$HOME/.config/claude-statusline"

Save the following as ~/.config/claude-statusline/statusline.py. It uses only the JSON it receives, a local clock to reject expired windows, and a read-only Git query anchored to the supplied workspace directory. It does not fetch usage data or read credentials or transcripts.

python
import json
import math
import re
import subprocess
import sys
import time


def obj(value):
    return value if isinstance(value, dict) else {}


def number(value):
    if not isinstance(value, (int, float)) or isinstance(value, bool):
        return False
    try:
        return math.isfinite(value)
    except OverflowError:
        return False


def text(value, fallback):
    if not isinstance(value, str):
        return fallback
    clean = " ".join("".join(c for c in value if c.isprintable()).split())
    return clean or fallback


def git_branch(directory):
    if not isinstance(directory, str) or not directory:
        return "git:-"
    try:
        result = subprocess.run(
            ["git", "-C", directory, "symbolic-ref", "--quiet", "--short", "HEAD"],
            capture_output=True, text=True, timeout=0.2, check=False,
        )
        if result.returncode == 0:
            return "git:" + text(result.stdout, "?")
        result = subprocess.run(
            ["git", "-C", directory, "rev-parse", "--short", "HEAD"],
            capture_output=True, text=True, timeout=0.2, check=False,
        )
        if result.returncode == 0:
            return "git:@" + text(result.stdout, "?")
    except (OSError, subprocess.TimeoutExpired, UnicodeError, ValueError):
        pass
    return "git:-"


def render(data):
    model = obj(data.get("model"))
    name = text(model.get("display_name"), text(model.get("id"), "model?"))
    workspace = obj(data.get("workspace"))
    directory = workspace.get("current_dir")
    if not isinstance(directory, str) or not directory:
        directory = data.get("cwd")
    folder = "workspace?"
    if isinstance(directory, str) and directory:
        folder = text(re.split(r"[\\/]", directory.rstrip("/\\"))[-1], "/")

    used = obj(data.get("context_window")).get("used_percentage")
    context = f"ctx:{used:.0f}%" if number(used) and 0 <= used <= 100 else "ctx:?"
    cost = obj(data.get("cost")).get("total_cost_usd")
    estimate = f"est:${cost:.2f}" if number(cost) and cost >= 0 else "est:$?"
    parts = [name, folder, git_branch(directory), context, estimate]

    window = obj(obj(data.get("rate_limits")).get("five_hour"))
    usage, reset = window.get("used_percentage"), window.get("resets_at")
    if number(usage) and 0 <= usage <= 100 and number(reset) and reset > time.time():
        parts.append(f"5h:{usage:.0f}% used")
    return " | ".join(parts)


def main():
    try:
        data = json.load(sys.stdin)
        if not isinstance(data, dict):
            raise ValueError("expected a JSON object")
    except (ValueError, UnicodeError) as error:
        print(f"statusline input error: {error}", file=sys.stderr)
        data = {}
    print(render(data))


if __name__ == "__main__":
    main()

The script prints one plain-text line. Diagnostic messages go to stderr, which is not the statusline display. Because the command below invokes Python explicitly, the script itself does not need an executable bit.

Test stdin and stdout before editing settings

Save this synthetic input as statusline-mock.json in your current directory:

json
{
  "model": {"id": "example-model", "display_name": "Example Model"},
  "workspace": {"current_dir": "/__statusline_example_missing__/demo"},
  "context_window": {"used_percentage": 42},
  "cost": {"total_cost_usd": 0.18},
  "rate_limits": {
    "five_hour": {"used_percentage": 20, "resets_at": 4102444800}
  }
}

The intentionally nonexistent workspace path keeps the Git result predictable. The reset timestamp is a future example in Unix seconds, not an account measurement. Run:

bash
python3 "$HOME/.config/claude-statusline/statusline.py" < statusline-mock.json

Expected stdout:

Example Model | demo | git:- | ctx:42% | est:$0.18 | 5h:20% used

Then try an empty object:

bash
printf '%s' '{}' | python3 "$HOME/.config/claude-statusline/statusline.py"

Expected stdout:

model? | workspace? | git:- | ctx:? | est:$?

That second result is useful: unknown context and cost remain unknown. With numerical zeros in the JSON, the script prints ctx:0% and est:$0.00. Invalid JSON prints an input error to stderr and the same fallback line to stdout.

Connect the script to statusLine

For a personal setup, add the following key to your user settings, normally ~/.claude/settings.json. Preserve every unrelated setting. This is a settings fragment, not an instruction to replace an existing file:

json
{
  "statusLine": {
    "type": "command",
    "command": "python3 \"/Users/YOUR_NAME/.config/claude-statusline/statusline.py\""
  }
}

Replace the sample path with your script's absolute path. On Linux, that might start with /home/YOUR_NAME/. If Claude Code cannot find python3, use the interpreter's absolute path too. Keep quotes around paths containing spaces, and escape those quotes inside JSON.

Claude Code reruns the command when the command setting changes. The success signal is your line appearing in the footer with session values replacing the mock values. An initial ctx:? can be normal before the first API response. The mock proves the script's input and output behavior; we validated these examples offline, without a live Claude Code UI or Windows client test.

Conceptual stdin JSON to Python formatter to stdout statusline flow, with a separate read-only Git query and stderr diagnostics

Use the current JSON fields correctly

The current official schema uses nested objects. Avoid older snippets that treat model as a string, read context_window.percentage, or assume a generic git.branch field exists.

DisplayCurrent inputMeaning and fallback
Modelmodel.display_name, then model.idBoth are inside the model object
Current directoryworkspace.current_dir, or cwdworkspace.project_dir is the launch directory and can differ
Context usedcontext_window.used_percentageMissing or null is unknown; a numeric 0 is valid
Session costcost.total_cost_usdClient-side USD estimate, not an invoice
Five-hour usagerate_limits.five_hour.used_percentagePercentage consumed, with an independently optional window
Reset timeThe window's resets_atUnix epoch seconds; discard an expired window
Ordinary Git branchA separate local Git lookupThere is no generic git.branch in the input

The example queries Git with git -C using the supplied directory. It shows a branch name for a normal or unborn branch, and git:@<short-hash> for a detached HEAD. A missing directory, unavailable Git, failed lookup, or timeout falls back to git:-. Linked worktrees are resolved by Git in their own directory; the script never silently substitutes its process's current directory. The 0.2-second timeout bounds each lookup attempt rather than proving a particular rendering speed.

Claude Code also supplies worktree-specific metadata, but workspace.git_worktree and worktree describe different situations. Some branch fields can be absent in hook-created worktrees. Check the documented shape before replacing a local branch query with those values.

Context, cost, and plan usage measure different things

Context percentage describes the live context from the latest API response. Its input-token total combines input tokens, cache-creation input tokens, and cache-read input tokens; output tokens are excluded from the used-percentage calculation. current_usage and percentages can be null before the first response or after /compact until the next response. /context can show a higher figure because it also estimates newly added, unsent messages. These distinctions are documented in the statusline guide.

cost.total_cost_usd is an estimated session cost using client-side list prices or modelPricing. It does not identify who gets charged and is not your subscription's remaining allowance. Since Claude Code 2.1.211, /clear starts a new session at zero; older versions carried that cost forward. Duration fields such as total_duration_ms are milliseconds, and session duration excludes time when the session was stopped.

rate_limits is available for eligible claude.ai Pro/Max subscriptions or the Claude apps gateway with spend limits, after the first API response. Five-hour, seven-day, and spend-limit windows can each be absent, and expired windows are removed. Their absence does not mean zero usage, unlimited capacity, or a broken API key. The script hides a five-hour window unless its percentage and future reset timestamp are usable.

If you add gateway spend widgets, check versions and units first: spend_limit.used_percentage can exceed 100 and requires 2.1.251. The optional used_usd, limit_usd, and period fields require 2.1.284 on both client and gateway. Dollar values are read separately about every five minutes, may lag the percentage, and can be absent when nonessential traffic is disabled. None of that changes the meaning of the session-cost estimate. See the field documentation before building calculations around these values.

Put the setting in the right scope

Use user settings for a personal home-directory script. Use project-local settings for a personal override in one project, and shared project settings for a team convention whose script and runtime are available to everyone.

ScopeCommon location or entryAppropriate use
User~/.claude/settings.jsonYour personal statusline across projects
Project-local.claude/settings.local.jsonYour private project override
Shared project.claude/settings.jsonA committed team configuration
Command line--settingsAn explicit temporary configuration
ManagedOrganization-controlled settingsAn administrator's policy or deployed command

For the same setting, precedence is managed, command line, project-local, shared project, then user. An omitted key retains lower-scope values; do not extrapolate that into a blanket rule that all objects or lists are replaced. /status shows loaded setting sources, although it does not attribute every effective key to a file. The settings documentation explains scope and precedence.

For Git worktrees, local settings can resolve to the main checkout's root, with platform, ownership, and older-version exceptions. Shared project settings are read from the primary working directory; /cd begins loading settings from the new directory in 2.1.246. Check the files actually loaded when an override seems to do nothing.

A shared command needs a deliberately chosen repo path and an agreed interpreter. Review local Git calls and other dependencies as you would any committed script. Moving a personal configuration into shared scope is a team rollout, not merely a styling change.

Fix a blank or skipped statusline

Start with the exact command from statusLine.command and feed it the mock JSON. A successful mock narrows the problem to configuration, execution context, or display behavior; it does not prove the client loaded that command.

What you observeNext checkWhat the result tells you
The mock produces no stdoutCheck interpreter path, script path, stderr, and exit statusFix the local command before debugging the UI
Only diagnostic text appears in your terminalSeparate stdout from stderrThe final display must be printed to stdout
The mock works but Claude Code has no lineInspect /status setting sources and configuration JSONAnother scope may override the command, or the file may not be loaded
The line appears with ctx:?Wait for the first response, or inspect your field nameMissing measurement differs from a command that did not run
A Git segment becomes git:-Query the supplied directory with Git directlyThe directory, Git availability, or lookup timeout needs investigation
Plain text works but styled output looks wrongRemove glyphs, ANSI colors, and links temporarilyTerminal rendering can be isolated from script execution

Current startup checks report malformed JSON and known invalid values. claude doctor can also report rejected settings; neither command is a reason to delete the whole settings file. See the settings reference for supported values.

If settings and the command look correct, check the documented execution gates:

  • Managed disableAllHooks: true, or an untrusted workspace: all custom statusline commands are disabled.
  • allowManagedHooksOnly, effective non-managed disableAllHooks: true, or --safe-mode: only a statusline supplied through managed settings can run. Personal, project, and plugin values are skipped; a managed command may still run.
  • A force-enabled managed plugin: permission to run its hooks does not automatically permit its statusline. The statusline setting itself must come from managed settings.

These are distinct cases in the managed-hooks reference. For an organization-controlled restriction, ask the administrator whether a managed statusline is supported. Do not turn off company policy as a generic repair. A trust restriction likewise needs a decision about the workspace, rather than a path workaround.

Conceptual statusline troubleshooting ladder separating mock command output, loaded settings, execution policy and stale or missing measurements

Fix stale output without confusing refresh with fresh data

Claude Code reruns the statusline at session start or resume, after assistant messages and /compact, on relevant mode changes, when the command changes, and at configured refresh intervals. It also reacts to expiry timestamps it has already received. Updates are debounced by 300 ms, and a new update cancels an in-flight script. Editing the script file takes effect at the next trigger. These behaviors are described in the official guide.

For the script above, an optional timer can pick up idle Git branch changes and remove an expired five-hour display:

json
{
  "statusLine": {
    "type": "command",
    "command": "python3 \"/Users/YOUR_NAME/.config/claude-statusline/statusline.py\"",
    "refreshInterval": 10
  }
}

The interval is in seconds, with a minimum of 1. It reruns the command; it does not make old upstream context or usage measurements fresh. This script has no cache. If you later cache expensive checks, include a stable session identity and directory in the cache key so one session or worktree cannot reuse another's state.

Slow commands can be canceled before they print. Remove network requests and large scans while diagnosing that case. Keep timeouts for subprocesses, and use COLUMNS if you add width-aware output: the statusline's stdout is captured rather than connected to a TTY, so tput cols or a language's TTY-size check is not the documented width source.

Multiple lines, ANSI colors, and OSC 8 links are supported where the terminal supports them. Terminal.app does not provide clickable OSC 8 links. Narrow terminals and notifications can crowd the row, and the bar can briefly disappear during help or permission prompts. Built-in footer badges remain below it. Those display conditions do not automatically mean the script failed.

Claude Code statusline on Windows

Current Claude Code uses Git Bash on Windows when it is installed, otherwise PowerShell. Choose a command that works in the shell Claude Code uses; do not assume every Windows setup runs through cmd.exe. The official Windows examples also support an explicit PowerShell script invocation.

The Python example needs an installed Python interpreter on Windows. Claude Code's native installation does not imply Python is present. Use absolute paths and forward slashes for command paths, for example:

json
{
  "statusLine": {
    "type": "command",
    "command": "C:/Python312/python.exe C:/Users/YOUR_NAME/claude-statusline/statusline.py"
  }
}

Those are example locations: replace both with your actual paths. Quote and JSON-escape either path if it contains spaces. The script accepts both slash styles in the supplied workspace path. For a PowerShell mock test, use the same interpreter and script:

powershell
Get-Content -Raw ./statusline-mock.json | & 'C:/Python312/python.exe' 'C:/Users/YOUR_NAME/claude-statusline/statusline.py'

Check the exit status and stdout, then test the configured command in the shell the client uses. This is a documented setup path and an offline-checked script, not a claim that we tested the Windows Claude Code interface. Start with ASCII output before introducing font-dependent Powerline symbols.

When ccstatusline is worth adding

Choose ccstatusline if configurable widgets, themes, and a TUI layout editor are more useful to you than maintaining a short script. Its README's quickstart uses npx -y ccstatusline@latest or bunx -y ccstatusline@latest; these fetch and execute a package and require the corresponding runtime. The initial TUI also offers a pinned global installation, which installs that version and writes a pinned command. After that installation, ccstatusline opens the TUI. Its configuration lives in ~/.config/ccstatusline/settings.json.

The widgets change the data access involved. Usage widgets can look up credentials, including Keychain credentials, and call Anthropic's usage API directly. Some metrics scan transcripts or caches, and service-health widgets use network data. It is therefore not an entirely offline wrapper around the official stdin JSON. Choose widgets with those dependencies in mind; our example above performs neither credential lookup nor usage requests. We did not install or run the formatter for this guide.

The formatter's TUI writes refreshInterval for supported Claude Code versions; its README identifies support from 2.1.97. Use its documented setup rather than an old ccstatusline init command. A plain script remains a practical choice if you only need a few supplied metrics and a local branch name.

FAQ

Is statusline the same as statusLine?

/statusline is the Claude Code slash command. statusLine is the case-sensitive settings key. “Statusline” and “status line” are common ways to describe the feature, but use the exact spelling when editing JSON.

Does displaying a statusline consume API tokens?

Printing the supplied JSON as text does not make an additional model request. A custom command can do other work, however, and a formatter may make network requests for particular widgets. Check the actual command's behavior rather than assuming every statusline is purely local. The official contract is stdin JSON and stdout text.

Why is the cost $0.00 while context usage is nonzero?

The two values measure different things: context is the latest response's live context, while cost is a client-side session estimate. In this example, cost is rounded to two decimal places, so a tiny positive estimate can also display as $0.00. Neither figure alone proves an invoice amount or subscription allowance. See the cost and context fields.

Can I show seven-day usage instead of five-hour usage?

Yes. Adapt the window lookup to rate_limits.seven_day, use a 7d label, and retain the type and expiry checks. Eligible windows are independently optional and appear after the first response; an absent window should be hidden or labeled unavailable, not reported as 0%. The schema documents these conditions.

How do I remove the statusline?

Ask /statusline to clear it, or remove only the statusLine key from the scope that defines it. Preserve other settings. If a lower scope defines another statusline, removing your override can reveal that one because settings have precedence. See statusline configuration and settings scopes.

Sources4

External pages this guide links to, in the order they appear. Last updated Oct 8, 2026.

  1. 1.official statusline guidecode.claude.com/docs/en/statusline
  2. 2.settings documentationcode.claude.com/docs/en/settings
  3. 3.settings referencecode.claude.com/docs/en/settings-reference
  4. 4.ccstatuslinegithub.com/sirmalloc/ccstatusline
More in Claude Code
Choosing bundled, official, and project-specific Claude Code skills for the work at hand
Claude Code

Best Claude Code Skills to Use First: Picks by Workflow

Use /code-review to look for bugs, /simplify to clean up changed code, and an official skill when design, browser testing, or document work needs a more specific method. Install for the right scope, then check discovery and a real task result.

12 min