Two things quietly derail long Claude Code sessions: the context window fills up and auto-compacts before you notice, wiping out critical decisions; or you forget about uncommitted Git changes and let Claude work on top of a dirty tree.

The default status line only shows the model name and context percentage. You cannot see your Git state, how fast you are burning tokens, or whether prompt caching is actually hitting—all essentials for long sessions.

Claude Code supports custom status lines: drop a script at a configured path and it refreshes every 5 seconds. Here is my full implementation, along with the key design decisions and the pitfalls I hit along the way.


Final Result

Two dense, scannable lines:

1
2
[GLM-5.1 Opus] my-project (main) +2 ~3 ?1 📌1 | 5m 12s | +156 -23
⚡ ██████████████░░░░░░ 47% [200K] [OK] ⚡2.3k/m | 📦85% | ⏳12%
Line Fields Question It Answers
Line 1 Model · Repo(branch) staged/modified/untracked Stash · Duration · Diff +/- lines “Where am I, and what changed?”
Line 2 Emoji · RGB progress bar usage%[capacity] · Status · Token speed · Cache hit rate · API wait “How much runway is left, and what’s slow?”

Installation

Step 1: Save the script to ~/.claude/statusline.sh and make it executable:

1
chmod +x ~/.claude/statusline.sh

Step 2: Add the statusLine block to ~/.claude/settings.json:

1
2
3
4
5
6
7
{
"statusLine": {
"type": "command",
"command": "~/.claude/statusline.sh",
"refreshInterval": 5
}
}

Restart Claude Code for the changes to take effect. The script depends on jq for JSON parsing—install it via sudo apt install jq -y if it is not already available.


Complete Script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#!/bin/bash
# Claude Code status line script
# Dependency: jq

# --- Read JSON and extract all fields in a single jq invocation ---
# Use SOH (\x01) as the delimiter instead of tab (bash read collapses adjacent whitespace and drops empty fields)
input=$(cat)
IFS=$'\001' read -r model session_id session_name cwd used ctx_size \
input_tokens output_tokens cache_creation cache_read \
duration_ms api_duration_ms lines_add lines_del <<< \
"$(echo "$input" | jq -j '[
.model.display_name // "Unknown",
.session_id // "default",
.session_name // "",
.workspace.current_dir // .cwd // "",
.context_window.used_percentage // "",
.context_window.context_window_size // 0,
.context_window.total_input_tokens // 0,
.context_window.total_output_tokens // 0,
.context_window.current_usage.cache_creation_input_tokens // 0,
.context_window.current_usage.cache_read_input_tokens // 0,
.cost.total_duration_ms // 0,
.cost.total_api_duration_ms // 0,
.cost.total_lines_added // 0,
.cost.total_lines_removed // 0
] | join("\u0001")')"

# --- Resolve configured model slot ---
model_id=$(echo "$input" | jq -r '.model.id // ""')
_haiku=$(jq -r '.env.ANTHROPIC_DEFAULT_HAIKU_MODEL // ""' ~/.claude/settings.json 2>/dev/null)
_sonnet=$(jq -r '.env.ANTHROPIC_DEFAULT_SONNET_MODEL // ""' ~/.claude/settings.json 2>/dev/null)
_opus=$(jq -r '.env.ANTHROPIC_DEFAULT_OPUS_MODEL // ""' ~/.claude/settings.json 2>/dev/null)
slot=""
[ "$model_id" = "$_opus" ] && slot="Opus"
[ "$model_id" = "$_sonnet" ] && [ "$model_id" != "$_opus" ] && slot="Sonnet"
[ "$model_id" = "$_haiku" ] && slot="Haiku"

# --- ANSI colors ---
CYAN='\033[36m'; GREEN='\033[32m'; YELLOW='\033[33m'; RED='\033[31m'
MAGENTA='\033[35m'; BOLD='\033[1m'; DIM='\033[2m'; RESET='\033[0m'

# --- Probabilistic cache cleanup (1% chance per run to avoid running find every tick) ---
[ $(( RANDOM % 100 )) -eq 0 ] && find /tmp -maxdepth 1 -name 'claude_statusline_*' -mtime +1 -delete 2>/dev/null

# --- Session duration ---
if [ "$duration_ms" -gt 0 ]; then
total_sec=$((duration_ms / 1000))
hrs=$((total_sec / 3600)); mins=$(( (total_sec % 3600) / 60 )); secs=$((total_sec % 60))
[ "$hrs" -gt 0 ] && time_str="${hrs}h ${mins}m" || time_str="${mins}m ${secs}s"
else
time_str="0m 0s"
fi

# --- Token throughput ---
total_tokens=$((input_tokens + output_tokens))
token_speed=0
[ "$duration_ms" -gt 0 ] && duration_sec=$((duration_ms / 1000))
[ "${duration_sec:-0}" -gt 0 ] && token_speed=$(( total_tokens * 60 / duration_sec ))
if [ "$token_speed" -ge 1000 ]; then
speed_str="$((token_speed / 1000)).$(( (token_speed % 1000) / 100 ))k/m"
else
speed_str="${token_speed}/m"
fi

# --- Cumulative cache hit rate (across the entire session) ---
# Detect new API calls via total_tokens changes and accumulate current_usage cache metrics
CACHE_ACC_FILE="/tmp/claude_statusline_cache_${session_id}"
if [ -f "$CACHE_ACC_FILE" ]; then
IFS='|' read -r acc_read acc_creation last_total < "$CACHE_ACC_FILE"
else
acc_read=0; acc_creation=0; last_total=0
fi
if [ "$total_tokens" != "$last_total" ] && [ "$total_tokens" -gt 0 ]; then
acc_read=$((acc_read + cache_read))
acc_creation=$((acc_creation + cache_creation))
printf '%s|%s|%s' "$acc_read" "$acc_creation" "$total_tokens" > "$CACHE_ACC_FILE"
fi
cache_total=$((acc_read + acc_creation))
[ "$cache_total" -gt 0 ] && cache_hit=$((acc_read * 100 / cache_total)) || cache_hit=-1

# --- API wait ratio ---
[ "$duration_ms" -gt 0 ] && api_pct=$((api_duration_ms * 100 / duration_ms)) || api_pct=0

# --- Context capacity label ---
if [ "$ctx_size" -ge 1000000 ]; then ctx_label="1M"
elif [ "$ctx_size" -ge 1000 ]; then ctx_label="$((ctx_size / 1000))K"
else ctx_label=""; fi

# --- Git status (5-second cache) ---
CACHE_FILE="/tmp/claude_statusline_git_${session_id}"
CACHE_TTL=5
if [ -f "$CACHE_FILE" ]; then
cache_age=$(( $(date +%s) - $(stat -c %Y "$CACHE_FILE" 2>/dev/null || echo 0) ))
else
cache_age=$((CACHE_TTL + 1))
fi
if [ "$cache_age" -gt "$CACHE_TTL" ]; then
branch="" repo="" remote_url="" staged=0 modified=0 stash=0 diff_add=0 diff_del=0 untracked=0
if [ -n "$cwd" ]; then
branch=$(git -C "$cwd" --no-optional-locks symbolic-ref --short HEAD 2>/dev/null)
repo=$(basename "$(git -C "$cwd" --no-optional-locks rev-parse --show-toplevel 2>/dev/null)" 2>/dev/null)
staged=$(git -C "$cwd" --no-optional-locks diff --cached --numstat 2>/dev/null | wc -l | tr -d ' ')
modified=$(git -C "$cwd" --no-optional-locks diff --numstat 2>/dev/null | wc -l | tr -d ' ')
stash=$(git -C "$cwd" --no-optional-locks stash list 2>/dev/null | wc -l | tr -d ' ')
untracked=$(git -C "$cwd" --no-optional-locks ls-files --others --exclude-standard 2>/dev/null | wc -l | tr -d ' ')
remote_url=$(git -C "$cwd" --no-optional-locks remote get-url origin 2>/dev/null \
| sed -E 's|git@([^:]+):(.+)\.git$|https://\1/\2|; s|\.git$||')
# Sum staged + unstaged git diff lines in a single awk pass
diff_stats=$( ( git -C "$cwd" --no-optional-locks diff --cached --numstat 2>/dev/null; \
git -C "$cwd" --no-optional-locks diff --numstat 2>/dev/null ) | \
awk '{add+=$1; del+=$2} END {print add+0"|"del+0}' )
diff_add=$(echo "$diff_stats" | cut -d'|' -f1)
diff_del=$(echo "$diff_stats" | cut -d'|' -f2)
fi
printf '%s' "${branch}|${repo}|${remote_url}|${staged}|${modified}|${stash}|${diff_add}|${diff_del}|${untracked}" > "$CACHE_FILE" 2>/dev/null
else
cache_line=$(cat "$CACHE_FILE" 2>/dev/null)
branch=$(echo "$cache_line" | cut -d'|' -f1)
repo=$(echo "$cache_line" | cut -d'|' -f2)
remote_url=$(echo "$cache_line" | cut -d'|' -f3)
staged=$(echo "$cache_line" | cut -d'|' -f4)
modified=$(echo "$cache_line" | cut -d'|' -f5)
stash=$(echo "$cache_line" | cut -d'|' -f6)
diff_add=$(echo "$cache_line" | cut -d'|' -f7)
diff_del=$(echo "$cache_line" | cut -d'|' -f8)
untracked=$(echo "$cache_line" | cut -d'|' -f9)
fi

# --- Line 1: Model + Git + Duration + Diff stats ---
if [ -n "$slot" ]; then
line1="${BOLD}[${model} ${DIM}${slot}${RESET}${BOLD}]${RESET}"
else
line1="${BOLD}[${model}]${RESET}"
fi
if [ -n "$repo" ]; then
if [ -n "$remote_url" ]; then
repo_part=$(printf '\e]8;;%s\a%s\e]8;;\a' "$remote_url" "$repo")
line1="${line1} ${BOLD}${repo_part}${RESET}"
else
line1="${line1} ${BOLD}${repo}${RESET}"
fi
fi
[ -n "$branch" ] && line1="${line1} ${CYAN}(${branch})${RESET}"
git_status=""
[ "${staged:-0}" -gt 0 ] && git_status="${GREEN}+${staged}${RESET}"
[ "${modified:-0}" -gt 0 ] && git_status="${git_status}${git_status:+ }${YELLOW}~${modified}${RESET}"
[ "${untracked:-0}" -gt 0 ] && git_status="${git_status}${git_status:+ }${MAGENTA}?${untracked}${RESET}"
[ -n "$git_status" ] && line1="${line1} ${git_status}"
[ "${stash:-0}" -gt 0 ] && line1="${line1} ${YELLOW}📌${stash}${RESET}"
line1="${line1} ${DIM}|${RESET}"
[ -n "$session_name" ] && line1="${line1} ${MAGENTA}${session_name}${RESET} ${DIM}|${RESET}"
line1="${line1} ${time_str} ${DIM}|${RESET}"
line1="${line1} ${GREEN}+${diff_add}${RESET} ${RED}-${diff_del}${RESET}"

# --- Line 2: Progress bar + Metrics + Warnings ---
BAR_WIDTH=20
if [ -n "$used" ]; then
used_int=$(printf '%.0f' "$used")
filled=$(( (used_int * BAR_WIDTH + 50) / 100 ))
bar=""
for (( i=0; i<BAR_WIDTH; i++ )); do
pos=$(( i * 100 / (BAR_WIDTH - 1) ))
if [ "$pos" -le 50 ]; then
r=$(( 220 * pos / 50 )); g=200; b=$(( 80 - 80 * pos / 50 ))
else
adj=$(( pos - 50 )); r=220; g=$(( 200 - 160 * adj / 50 )); b=$(( 20 * adj / 50 ))
fi
if [ "$i" -lt "$filled" ]; then
bar="${bar}\033[38;2;${r};${g};${b}m█"
else
bar="${bar}\033[38;2;60;60;60m░"
fi
done
bar="${bar}${RESET}"

if [ "$used_int" -ge 84 ]; then emoji="🚨"
elif [ "$used_int" -ge 60 ]; then emoji="🔥"
elif [ "$used_int" -ge 20 ]; then emoji="⚡"
else emoji="🟢"; fi

if [ "$used_int" -ge 84 ]; then pct_color="$RED"
elif [ "$used_int" -ge 60 ]; then pct_color="$YELLOW"
else pct_color="$GREEN"; fi

[ -n "$ctx_label" ] && size_part=" ${DIM}[${ctx_label}]${RESET}" || size_part=""
[ "$token_speed" -gt 0 ] && speed_part=" ${DIM}|${RESET} ⚡${speed_str}" || speed_part=""

if [ "$cache_hit" -ge 0 ]; then
if [ "$cache_hit" -ge 80 ]; then cache_color="$GREEN"
elif [ "$cache_hit" -ge 50 ]; then cache_color="$YELLOW"
else cache_color="$RED"; fi
cache_part=" ${DIM}|${RESET} 📦${cache_color}${cache_hit}%${RESET}"
else cache_part=""; fi

if [ "$api_pct" -ge 60 ]; then api_part=" ${DIM}|${RESET} ⏳${RED}${api_pct}%${RESET}"
elif [ "$api_pct" -ge 30 ]; then api_part=" ${DIM}|${RESET} ⏳${YELLOW}${api_pct}%${RESET}"
else api_part=" ${DIM}|${RESET} ⏳${GREEN}${api_pct}%${RESET}"; fi

if [ "$used_int" -ge 84 ]; then
warn="${RED}[Critical → run /compact now to keep current progress & key decisions]${RESET}"
elif [ "$used_int" -ge 75 ]; then
warn="${YELLOW}[High → /compact to keep current progress & key decisions]${RESET}"
elif [ "$used_int" -ge 60 ]; then
warn="${YELLOW}[Elevated → /compact to keep current progress & key decisions]${RESET}"
else
warn="${GREEN}[OK]${RESET}"
fi

line2="${emoji} ${bar} ${pct_color}${used_int}%${RESET}${size_part} ${warn}${speed_part}${cache_part}${api_part}"
else
line2="🟢 \033[38;2;60;60;60m░░░░░░░░░░░░░░░░░░░░${RESET} --% ${GREEN}[OK]${RESET}"
fi

printf '%b\n' "$line1"
printf '%b\n' "$line2"

Design Decisions & Pitfalls

From 15 jq Calls Down to 1

My first draft used 15 separate jq -r invocations to pull out each field—spawning 15 subprocesses every 5 seconds. For a high-frequency status line, that overhead was immediately noticeable.

Switching to join("\u0001") extracts every field in one pass, using ASCII SOH (\x01) as the delimiter. Why not tab? Bash’s read collapses consecutive whitespace characters by default, which silently drops empty fields and shifts every variable after them out of alignment. \x01 is an invisible control character that will not appear in JSON values.

Preventing Git Lock Contention: --no-optional-locks

I added this flag only after getting burned without it. When the status line ran git diff every 5 seconds, it occasionally collided with a git add or git commit executed by Claude Code, causing intermittent index.lock file exists failures.

--no-optional-locks tells Git: “This is a read-only inspection—do not lock the index.” Because the status line never mutates the repository, adding this flag eliminated the lock collisions completely.

Cache Hit Rate: Not What It Looks Like

The cache_read_input_tokens and cache_creation_input_tokens values that Claude Code passes in are scoped to the single most recent API call, not the cumulative session total. Computing a hit rate directly from per-call numbers causes the percentage to bounce wildly every 5 seconds, making it useless.

My workaround: persist the previous token total in a temp file. Whenever total_tokens changes (indicating a new API call completed), accumulate the new cache read and creation counts. That gives you a true cumulative hit rate across the whole session.

Clicking (Ctrl+Click) the repository name opens the repo directly on GitHub via the terminal OSC 8 hyperlink escape sequence:

1
printf '\e]8;;https://github.com/user/repo\auser/repo\e]8;;\a'

The format is \e]8;;URL\aTEXT\e]8;;\a. It works out of the box in iTerm2, Windows Terminal, and the VS Code integrated terminal. Terminals that do not support OSC 8 simply render plain text with no visual breakage.

Cleaning Up Temporary Files

Both the Git status cache and the cache-hit accumulator write state files under /tmp, which would pile up over time. Running find /tmp -delete on every refresh is wasteful, so the script triggers cleanup probabilistically: RANDOM % 100 runs the sweep roughly 1% of the time. Runtime overhead stays near zero, while stale files never grow unbounded.


Summary

Signal Purpose What to Watch For
Git staged / modified / untracked / stash Workspace state Catch uncommitted edits or stray files before prompting
Context progress bar Remaining runway >60%: consider /compact; >84%: compact immediately
Token throughput Burn rate Sudden spikes often indicate repetitive loops
Cache hit rate Prompt cache efficiency <50% means poor cache reuse and higher token cost
API wait ratio Performance bottleneck >60% means most of the session is spent waiting on the API

Feel free to adapt the script to your own workflow—for example, displaying MCP server health or the active Skill name. Claude Code passes a rich JSON payload on stdin; pipe it through echo "$input" | jq . to inspect every available field.


Series Navigation