Skip to content

This site uses optional Google Analytics cookies to understand how it is used. Privacy notice

Blog index

Development / Tools / Productivity

My Claude Code Setup: Hooks, Shell Functions and a Status Line

The hooks, shell functions and settings I added to Claude Code, from forking the session before compaction to naming sessions after the folder, all kept in a dotfiles repo.

/ 11 min read

An infiniterm window with a Claude Code session named Meeting-Excuses. Claude has ranked ten believable excuses for an unfinished feature and is working on ten more, with the spinner reading You can't handle the truth. Below the prompt box, the custom status line shows the model, folder, context bar, cost, duration, a dated last-responded time and the 7-day rate limit.

Claude Code is where most of my work happens now (I wrote about the rest of the setup in My AI Workstation). Out of the box it is good. After a few months of small annoyances, it is also very much mine.

This post is a tour of what I changed: hooks that start a second Claude, sessions that know their own name, a status line that tells me more than I probably need, and 135 film quotes. If you already use Claude Code and want ideas beyond the defaults, take what you like. The official docs for hooks, settings and the status line cover everything used here.

Everything lives in a dotfiles repo

Before any of the fun parts: none of this is edited in place. My settings.json, CLAUDE.md, statusline.sh and every hook script live in a private dotfiles repo and are symlinked into ~/.claude.

That gives me two things. A new Mac gets the whole setup from one bootstrap script. And every tweak is a commit, so when an experiment goes wrong I can see what I changed and roll it back. That safety net is the reason I try so many experiments in the first place.

Hooks that start a second Claude

Hooks are shell commands Claude Code runs at fixed points: before a tool call, when a session starts, before compaction and so on. A hook can block an action or add text to the context, but it cannot tell the running session "go do this now". It can, however, start another Claude.

Docs updated before compaction

I used to type "update the docs" before every /compact. I forgot about half the time, and the details that never made it into CLAUDE.md were gone for good once the conversation was summarised.

Now a PreCompact hook does it when I run /compact by hand. It skips automatic compaction, and /compact clean skips it for the times another session already edited the files. It forks the live session headlessly:

claude -p --resume "$sid" --fork-session \
  --no-session-persistence --permission-mode acceptEdits \
  --allowedTools "Read,Edit,Write,Glob,Grep"
bash

The fork still sees the full, uncompacted conversation, so it knows what changed in this session. It gets a short prompt asking it to update CLAUDE.md and README.md in place, in their existing voice, and not to commit. The original session then compacts as normal.

There is one catch: the compacted session does not know the files changed under it. So a SessionStart hook with the compact matcher tells it to re-read those files before touching them. Whatever a SessionStart hook prints goes into the new context, so the whole hook is one echo:

echo "Note: ${files[*]} in $cwd were updated automatically" \
  "just before this compaction. Re-read them before editing;" \
  "do not redo the update."
bash

Session titles from Haiku

A UserPromptSubmit hook sends the first prompt of a session to Haiku (claude -p --model haiku --no-session-persistence) and asks for a 5 to 10 word summary. The result goes into a small TSV log with the date, session id and folder. It is not the visible name (that is the folder, see below), but it keeps a readable summary of what each session was about.

The hook calls claude, which would submit a prompt, which would trigger the hook again. An environment variable set by the hook stops that loop before it starts.

Calling claude -p from a hook has two more traps, and I hit both. A stray API key in the environment quietly moves the call from my subscription to API billing. And inside an infiniterm card, the titler's own hook events were credited to the card and overwrote its session id with one that has no transcript, which broke claude --resume there. The call now runs in a subshell that clears both first:

(
  unset ANTHROPIC_API_KEY ANTHROPIC_AUTH_TOKEN CLAUDE_API_KEY
  unset INFINITERM_CARD_ID
  title="$(CCT_AUTOTITLE_RUNNING=1 claude -p "$title_prompt" \
    --model haiku --no-session-persistence)"
  # ...clean up "$title" and append it to the TSV log
) &
disown
bash

--no-session-persistence keeps the titler from leaving its own transcript behind. The title is captured rather than printed, because whatever a UserPromptSubmit hook prints is added to the context. The subshell runs in the background, so the hook returns without waiting for Haiku.

Sessions named after the folder

I run several sessions at once, and they message each other. Telling one to "send this to notebook-49" is not great. I wanted every session named after its folder, so the session in my dotfiles repo is simply zshFiles.

First, a dead end worth sharing. /rename works by appending a custom-title event to the transcript. A hook can append the same event, and it lands in the file correctly. The running session ignores it. Only /rename or the CLI flag change the live name. For a while I showed the transcript's title in my status line as a workaround, then deleted it a few minutes later once the real fix worked.

So the fix moved out of Claude Code and into zsh. A function shadows claude and adds --name with the folder name for new interactive sessions:

function claude() {
  local arg
  if [[ $# -gt 0 && "$1" != -* ]]; then
    command claude "$@"; return
  fi
  for arg in "$@"; do
    case "$arg" in
      -n|--name|--name=*|-p|--print|-c|--continue|\
      -r|--resume|--resume=*)
        command claude "$@"; return ;;
    esac
  done
  command claude --name "${PWD:t}" "$@"
}
zsh

Subcommands, -p, resume, continue and an explicit name pass through untouched. The name shows at the top right of the prompt box, in /resume and in the agent list.

Resume where I left off

claude --continue resumes the most recent session in a folder, which is not always the one I want. So a SessionEnd hook records the last session id per folder, and a clr shell function resumes that one, falling back to claude --continue when nothing is recorded. The hook writes one file per folder, named by a hash of the path, so nothing lands inside a project:

function clr() {
  local key id
  key="$(printf '%s' "$PWD" | shasum | cut -d' ' -f1)"
  id="$(cat "$HOME/.claude/last-sessions/$key" 2>/dev/null)"
  if [[ -n "$id" ]]; then
    claude --resume "$id" "$@"
  else
    claude --continue "$@"
  fi
}
zsh

As a bonus, a pair of zsh hooks pushes claude --resume <id> into my shell history after a session exits. preexec notes when a claude command starts, and precmd checks whether a newer session id was written since:

_claude_resume_precmd() {
  [[ -n "$_claude_resume_start" ]] || return
  local start=$_claude_resume_start newest
  _claude_resume_start=
  newest=( ~/.claude/last-sessions/*(N.om[1]) )
  (( $#newest )) || return
  (( $(zstat +mtime -- "$newest[1]") >= start )) || return
  print -s -- "claude --resume $(<"$newest[1]")"
}
zsh

Up arrow, enter, and I am back.

Obsidian as the agents' memory

A SessionStart hook finds the Obsidian vault project that matches the current repo and prints its overview into the session. Every session starts knowing what the project is, where it lives, its stack and status, and which notes exist about it. It also lists any open handoffs from earlier sessions.

The vault rules live in one file that both Claude Code (through an @ import in CLAUDE.md) and Codex (through AGENTS.md) read. Agents write dated log notes, decision notes and handoffs, and keep a backlog. Short phrases like "note this" or "todo this" trigger small skills that do the filing.

I covered the full setup in Using Obsidian as Long-Term Memory for Claude, Codex and Cursor, so I will not repeat it here.

Notifications and unattended jobs

Stop and Notification hooks send me a Telegram message, "Done" or "Needs attention". They skip it when the terminal is focused and the screen is not locked, because I do not need my phone to tell me about something I am looking at.

The check fails open. If the script cannot tell which app is in front, it sends, because a notifier that stays quiet when unsure is worse than one that sends too often. The whole decision is one line:

[[ $force == 1 ]] ||
  { terminal_focused && ! screen_locked && exit 0; }
bash

terminal_focused walks up the process tree to the .app that owns the shell and compares it with the frontmost app from lsappinfo. screen_locked reads CGSSessionScreenIsLocked from ioreg.

A macOS LaunchAgent runs a skill headlessly through claude -p once a week, which writes a weekly work report and sends it to Telegram. It is the same skill I can run by hand, just on a schedule. The script it runs sends the result with TG_FORCE=1, which skips the focus check and the on/off switch, because nobody is watching the terminal at that hour anyway.

Guard rails

Two rules I want enforced, not just requested.

No Co-Authored-By trailers. Setting attribution.commit to an empty string stops Claude Code from adding one, but the model can still type it into a commit message. A PreToolUse hook blocks that. Exit code 2 refuses the tool call, and whatever goes to stderr is shown to the model, so it knows what to fix:

cmd=$(jq -r '.tool_input.command // empty')
if printf '%s' "$cmd" | grep -qi 'co-authored-by'; then
  echo "Commit refused: remove the Co-Authored-By trailer." >&2
  exit 2
fi
sh

The if field in settings.json means the script only runs for commit commands, not every Bash call:

{
  "matcher": "Bash",
  "hooks": [
    {
      "type": "command",
      "command": "~/.claude/hooks/no-coauthor.sh",
      "if": "Bash(*git*commit*)"
    }
  ]
}
json

No in-place edits from the shell. Deny rules block sed -i and perl -i in their common spellings:

"deny": [
  "Bash(sed -i*)",
  "Bash(sed * -i*)",
  "Bash(perl -pi*)",
  "Bash(perl -i*)"
]
json

Every file edit goes through the Edit and Write tools instead, and those are the only edits /rewind can undo.

Small rules in CLAUDE.md

Not everything needs a hook. My global CLAUDE.md has a handful of one-line rules that each remove a small, recurring annoyance:

- When I reply with a single plus sign (`+`), interpret it as a positive response. It means "Yes", "OK", "Proceed", "Continue", or "I approve."
- When you give me text to copy and paste, put it between two `---` lines. Everything between the markers must be paste-ready.
- "Check the screenshot" means the most recently saved screenshot file in `~/Downloads`. Open it without asking which file.
- Never download files or run downloaded third-party code yourself. Give me the exact command and wait for my result.
- Before any action that moves the pointer, types or takes focus, tell me what you are about to do and wait for my confirmation.
markdown

The + rule turns every confirmation into one keystroke. The download rule keeps me in the loop: the agent can read and write my code, but anything fetched from the internet runs only after I have seen the command.

Look and feel

A status line with opinions

My status line is a two-line shell script. It shows:

  • The model and the folder.
  • The git branch, with counts for modified, untracked and deleted files and ahead/behind arrows.
  • A context bar that changes colour as it fills.
  • Session cost and duration.
  • A "last responded" timestamp that includes the date. A plain time like "14:02" looks fresh even when it is from yesterday. With the date, a stale value looks stale.
  • The 5-hour and 7-day rate limits.

The timestamp trick works because the status line re-renders after each Claude response (and on mode changes), not on a timer. The current time at render is the "last responded" time, and it stays frozen on screen until the next render:

NOW_FMT=$(date '+%d/%m %H:%M:%S')
bash

A session left for two days shows "03/12 21:49:38", which is obviously old. A bare "21:49:38" looks like it happened a minute ago.

Film quotes instead of spinner verbs

spinnerVerbs in replace mode swaps the default "thinking" words for my own list. Mine is 135 film quotes, so while Claude works I get "Houston, we have a problem" or "Great Scott!". It changes nothing about the work and I would not give it up.

"spinnerVerbs": {
  "mode": "replace",
  "verbs": [
    "May the Force be with you",
    "Houston, we have a problem",
    "You shall not pass!"
  ]
}
json

Defaults I changed

{
  "model": "opus[1m]",
  "effortLevel": "high",
  "cleanupPeriodDays": 365,
  "permissions": { "defaultMode": "auto" }
}
json

That is the 1M-context Opus model, high effort, and auto mode. With cleanupPeriodDays at 365, transcripts stay for a year instead of the default 30 days. A backfill skill reads old transcripts to write vault notes about past work.

Plugins

From the official marketplace I use the LSP plugins for the languages I work in (TypeScript, Swift, Rust, Python, Ruby, C), so Claude gets real diagnostics and go-to-definition instead of guessing. I also use frontend-design and the Sentry plugin.

Beyond those:

  • caveman makes replies terse. Answers get shorter and cost fewer tokens, while code, commands and error messages stay exact. It reads well in a terminal.
  • claude-code-mods by the author of infiniterm. I use two of its mods: tool-oneline puts each tool call on a single line, and prompt-box restyles the prompt box.

Third-party marketplaces go in extraKnownMarketplaces:

"extraKnownMarketplaces": {
  "caveman": {
    "source": {
      "source": "github",
      "repo": "JuliusBrussee/caveman"
    }
  },
  "ekinertac-mods": {
    "source": {
      "source": "github",
      "repo": "ekinertac/claude-code-mods"
    }
  }
}
json

The plugins docs explain how marketplaces and installs work.

The pattern behind it

Looking back, most of this follows one idea. A hook cannot talk to the running session, but it can fork it, write files next to it, or shape how the next session starts. Once I stopped trying to steer the live session from a hook and started working around it, most problems had a simple fix.

The other half is the dotfiles repo. When every change is a commit, trying something odd costs a few minutes, and undoing it costs one command. That is how a setup ends up with film quotes in the spinner.

TK° / Blog
Switch to dark mode