Claude Code / Tutorial

Claude Code Tutorial: Install, Login, CLAUDE.md, Permission Modes and Common Commands

This guide is for graduate students and engineers who use Claude Code to write research code and analyze data. Content is checked against the current official docs at code.claude.com/docs; commands, settings fields and errors were tested on Claude Code 2.1.296 (macOS arm64) without logging in or making paid calls.

Short answer

Claude Code is Anthropic's terminal coding agent. Install it with the official native script curl -fsSL https://claude.ai/install.sh | bash (on Windows, the PowerShell irm command), or with Homebrew, WinGet or npm (Node.js 22+). Login requires a Claude Pro subscription ($20/month) or higher, or a Console API key; the free plan does not include Claude Code. To use a gateway, set ANTHROPIC_BASE_URL and ANTHROPIC_AUTH_TOKEN in the env block of ~/.claude/settings.json. Project rules go in a root CLAUDE.md, and hard limits go in settings.json deny rules or hooks. Since 2.1.283 interactive sessions start in auto permission mode; switch with Shift+Tab. Run long jobs independently with nohup or a job scheduler, and resume sessions with claude --resume.

Step 1

Every route installs the same native binary. They differ in auto-update, whether Node.js is needed, and which interface you work in.

Older tutorials tell you to install Node.js first. Today only the npm route needs Node.js 22 or later; on an older Node, npm prints an EBADENGINE warning and the install still completes.

On shared home directories (NFS, common on HPC clusters), a running session keeps reading the executable. An in-place npm upgrade on another node deletes the old binary, and the running session exits with Bus error. On clusters, install the binary on local disk, or set DISABLE_UPDATES and let the admin upgrade centrally. An older bug where Claude Code exited immediately on SLURM compute nodes was fixed in 2.1.76 (GitHub #12507).

Install and verifybash
# macOS / Linux / WSL: native install (recommended, updates in the background)
curl -fsSL https://claude.ai/install.sh | bash
# Stable channel: about one week behind latest, skips releases with major regressions
curl -fsSL https://claude.ai/install.sh | bash -s stable

# Windows PowerShell (prompt starts with PS)
irm https://claude.ai/install.ps1 | iex
# Windows CMD (prompt without PS)
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

# Package managers (no auto-update)
brew install --cask claude-code          # stable channel; claude-code@latest follows latest
winget install Anthropic.ClaudeCode

# npm (requires Node.js 22+; do not use sudo)
npm install -g @anthropic-ai/claude-code
npm install -g @anthropic-ai/claude-code@latest   # use this to upgrade, not npm update -g

# Verify
claude --version     # tested on this page: 2.1.296 (Claude Code)
claude doctor        # read-only diagnostics: install method, auto-update, settings validation
RouteCommand or entry pointAuto-updateBest forNotes
Native install scriptcurl -fsSL https://claude.ai/install.sh | bashYes, in the backgroundPersonal machines, WSL, servers without rootInstalls to ~/.local/bin without admin rights; open a new terminal before running claude
Homebrewbrew install --cask claude-codeNo, brew upgrademacOS users who manage software with brewclaude-code follows the stable channel, claude-code@latest follows latest
WinGetwinget install Anthropic.ClaudeCodeNo, winget upgradeNative WindowsUpgrading while running can fail because the file is locked
npmnpm install -g @anthropic-ai/claude-codePossible, if the global directory is writableExisting Node 22+ setupsnpm only downloads the native binary; Node is not used at runtime; no sudo
apt / dnf / apkOfficial signed repositoriesNoCluster admins deploying centrallySuits machines with NFS-shared homes; see Bus error below
Desktop appclaude.com/downloadYesPeople who prefer not to use a terminalLinux has its own page; the GUI shows diffs and parallel sessions
VS Code / JetBrains extensionSearch Claude Code in the marketplaceWith the extensionReviewing diffs in the IDEThe VS Code extension reads its own setting for the starting permission mode, not project settings
Web cloud sessionsclaude.ai/codeNot neededLong tasks that continue offlineSubscription accounts only, needs a connected GitHub repository; local API keys are not used
Sources: official Advanced setup, Platforms and Authentication docs.

Windows

Use native Windows when your projects and tools live on Windows. Use WSL 2 when you depend on a Linux toolchain (conda, gcc, HPC scripts) or need the sandbox.

Native Windows

No admin rights needed. Git for Windows is optional: with it, commands run in Git Bash; without it, Claude Code falls back to the PowerShell tool. If Claude Code cannot find Git Bash, set CLAUDE_CODE_GIT_BASH_PATH to C:\Program Files\Git\bin\bash.exe in the env block of settings.json. Native Windows does not support the Bash sandbox.

WSL 2

Run the Linux install script inside the WSL terminal, not from PowerShell. Keep projects under /home: under /mnt/c, cross-filesystem I/O is slow and the official docs note that search returns fewer results, while claude doctor still reports Search OK.

npm installs inside WSL

If which node prints a path starting with /mnt/c/, WSL is using the Windows Node and you get exec: node: not found or a platform mismatch. Run npm config set os linux first, or install Node inside WSL with nvm. The native install script avoids this class of problems.

Logging in from WSL, SSH or containers

When the browser cannot call back to the local port, the login page shows a code; paste it at the Paste code here if prompted line in the terminal. If the browser does not open, press c to copy the login URL.

A file named nul appears in the project

Early versions wrote Unix-style /dev/null redirects on Windows (GitHub #4928). Upgrade to the latest version; if Explorer cannot delete an existing nul file, remove it from Git Bash with rm ./nul.

Install command in the wrong shell

The token '&&' is not a valid statement separator means you ran the CMD command in PowerShell; 'irm' is not recognized means you ran the PowerShell command in CMD. A prompt starting with PS is PowerShell.

Step 2

The first run of claude opens a browser login. When several credentials exist, Claude Code picks one in a fixed order; /status shows which one is active.

Credential precedence from high to low: cloud provider variables (CLAUDE_CODE_USE_BEDROCK and others), ANTHROPIC_AUTH_TOKEN, ANTHROPIC_API_KEY, an apiKeyHelper script, CLAUDE_CODE_OAUTH_TOKEN, browser login. A subscriber with a stale ANTHROPIC_API_KEY left in the shell sees a successful login followed by authentication errors on requests; unset ANTHROPIC_API_KEY and confirm with /status that the subscription is active again.

Login credentials are stored in the macOS Keychain, and in ~/.claude/.credentials.json on Linux and Windows. To use two accounts on one machine, separate them with CLAUDE_CONFIG_DIR, for example alias claude-lab='CLAUDE_CONFIG_DIR=~/.claude-lab claude'.

After upgrading your plan on claude.ai, the token in an existing session still reflects the old plan, and choosing Opus reports not available with the Claude Pro plan; run /logout and then /login.

MethodHow to set itBillingDifferences
Claude subscription (Pro, Max, Team, Enterprise)Run claude and sign in to your claude.ai account in the browserIncluded in the plan, limited by 5-hour session and weekly allowances1-hour prompt cache; web cloud sessions and Remote Control available; the free plan does not include Claude Code
Console API keyexport ANTHROPIC_API_KEY=...; interactive mode asks once to approve itPer token, see the pricing table belowPrompt cache defaults to 5 minutes; the dollar figure in /usage is a local estimate at list price
Gateway or relay (ANTHROPIC_BASE_URL)ANTHROPIC_BASE_URL + ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEYSet by the gateway operatorNo Remote Control; MCP tool search off by default; model names mapped with environment variables
Bedrock / Agent Platform / FoundryCLAUDE_CODE_USE_BEDROCK=1 and similar, or choose 3rd-party platform at the login screenCloud provider billAuto mode supports only newer models such as Sonnet 5 and Opus 4.7 or later
Long-lived tokenclaude setup-token creates a one-year token; set it as CLAUDE_CODE_OAUTH_TOKENSubscriptionFor CI and servers without a browser; --bare mode does not read it
Sources: official Authentication, Setup and Costs docs.

Use in China

For choosing an approach in mainland China (official subscription, relay, domestic models, cloud environment), see the comparison page How to use Codex and Claude Code in China. This section covers operations only: where the variables go, how to verify them and how to debug errors.

The model set in ANTHROPIC_DEFAULT_HAIKU_MODEL also runs background tasks such as session titles and summaries. Many relay tutorials point it at the retired claude-3-5 series, and background requests then fail repeatedly; point it at a model the gateway currently serves.

When the same variable is set both in the shell and in the env block of settings.json, settings.json wins. CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 also turns off auto-updates, so run claude update manually from time to time.

Verify the gateway from your shell firstbash
# Export the two variables in your shell, then verify the URL and credential with a 1-token request
export ANTHROPIC_BASE_URL=https://gateway.example.com
export ANTHROPIC_AUTH_TOKEN=sk-xxxx
curl -sS -w '\n%{http_code}\n' -X POST "$ANTHROPIC_BASE_URL/v1/messages" \
  -H "Authorization: Bearer $ANTHROPIC_AUTH_TOKEN" \
  -H "anthropic-version: 2023-06-01" -H "content-type: application/json" \
  -d '{"model":"claude-sonnet-4-6","max_tokens":1,"messages":[{"role":"user","content":"."}]}'
# {"id":"msg_... means it works; an "unknown model" error also proves the URL and credential are valid;
# 401 means switch to the x-api-key header and ANTHROPIC_API_KEY
# Inside claude, run /status and confirm the Anthropic base URL and Auth token lines
After verification, write it to ~/.claude/settings.json (user level; do not put credentials in the committed .claude/settings.json)json
{
  "env": {
    "ANTHROPIC_BASE_URL": "https://gateway.example.com",
    "ANTHROPIC_AUTH_TOKEN": "sk-xxxx",
    "ANTHROPIC_DEFAULT_SONNET_MODEL": "model-name-from-your-gateway",
    "ANTHROPIC_DEFAULT_HAIKU_MODEL": "small-model-name-from-your-gateway",
    "CLAUDE_CODE_MAX_CONTEXT_TOKENS": "128000",
    "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
    "API_TIMEOUT_MS": "600000"
  }
}
SymptomCauseFix
curl works but claude still asks you to log inThe credential is in the project .claude/settings.json, which interactive sessions read only after the first-run wizard and trust dialogMove env to ~/.claude/settings.json, or export it in the shell that starts claude
401 invalid tokenAUTH_TOKEN goes in Authorization: Bearer, API_KEY in x-api-key, and the gateway reads only oneSwitch to the other variable; do not set both
Startup warns about two credential sources and auth may not work as expectedA gateway variable and a saved login are both presentRun /logout to use the gateway; unset the variable to use the subscription
400 Extra inputs are not permitted or context_managementThe upstream rejects pre-release fields that Claude Code sendsAdd CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1 to env
400 Input tag 'adaptive' or thinking type should be enabled or disabledThe upstream model does not support adaptive thinkingThe official CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1 only affects Opus 4.6 and Sonnet 4.6; for other models the gateway operator must upgrade the upstream
400 ContextWindowExceededError or prompt token count exceeds the limitThe gateway's context is smaller than Claude Code assumes, and the rewritten error does not trigger auto-compactionRun /compact first; then set CLAUDE_CODE_MAX_CONTEXT_TOKENS or CLAUDE_CODE_AUTO_COMPACT_WINDOW (plain integers; 500k is read as 500)
Gateway models missing from /modelModel names are not in the built-in listSet CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1, or map names with ANTHROPIC_DEFAULT_SONNET_MODEL and related variables
Connection refused (ECONNREFUSED) after a long silent waitWrong address or the gateway is down; Claude Code retries 10 times by defaultTested here: 2 min 56 s before the error by default, 5.9 s with CLAUDE_CODE_MAX_RETRIES=0; remove the variable after debugging
Still no connection after setting a proxyClaude Code does not support SOCKS proxiesPoint HTTPS_PROXY at your proxy client's HTTP port, for example http://127.0.0.1:<HTTP port>
SSL certificate verification failed while curl worksThe runtime does not trust your company's or proxy client's root certificateSet NODE_EXTRA_CA_CERTS to the CA certificate file
Sources: official Connect to an LLM gateway troubleshooting table, Network configuration, Model configuration; retry timings tested on this page.

Pricing

Choose a subscription if you use it several hours a day. Choose the API for occasional use, scripts and CI, or when you need exact accounting. Prices below are the official public prices on 2026-10-10 (USD, before tax).

Reference spend

Official figures from enterprise deployments: about $13 per developer per active day and $150–250 per month, with 90% of users below $30 per active day.

Cache lifetime sets the cost of a break

The prompt cache lives 1 hour on a subscription and 5 minutes by default on an API key. With an API key, a question after a break longer than 5 minutes rereads the whole context at the uncached price. In a long session, even a one-line question is billed against the whole context.

Checking usage

/usage (aliases /cost and /stats) shows session tokens and the estimated cost; subscribers see allowance bars and reset times. A warning appears at about 85% of an allowance. When the separate Opus or Sonnet limit runs out, /model to the other family keeps you working; session and weekly limits are shared across models.

Caps for scripts

claude -p supports --max-budget-usd and --max-turns and stops when a cap is reached. The amount is a client-side estimate and can slightly overshoot, so leave headroom.

PlanPriceNotes
Free$0Does not include Claude Code
Pro$20 billed monthly; $17/month billed annually ($200 up front)Includes Claude Code; allowance counted in 5-hour session windows and weekly windows
MaxFrom $100/month, with 5x or 20x Pro usagePriority access at peak times; includes monthly API credits
API: Claude Sonnet 5.5$2 input / $10 output per million tokens; cache hits $0.10Default choice for everyday coding
API: Claude Opus 5.5$4 input / $20 output; cache hits $0.20Complex planning and multi-step reasoning
API: Claude Haiku 5.5$0.10 input / $0.50 output ($0.50 / $2.50 for prompts over 100,000 tokens)Simple subagent tasks
API: Claude Fable 5.1$10 input / $50 output; cache hits $0.25Top tier
Sources: claude.com/pricing and the Claude API Pricing page.

Step 3

CLAUDE.md is an instruction file read at the start of each session. It shapes how Claude works; it does not limit what Claude can do. Limits that must hold go in permission rules or hooks.

CLAUDE.md example for a research projectmarkdown
# Project: differential expression analysis of single-cell data

## Directory conventions
- data/raw/: raw data, read-only. Do not modify, move or delete, and do not unpack or sort in place.
- data/processed/: generated from raw by scripts in scripts/; can be deleted and rebuilt at any time.
- scripts/: every analysis step, numbered 01_, 02_, each runnable on its own.
- results/: figures and tables, file names prefixed with the script number, e.g. 03_volcano.pdf.
- logs/: one log per run, file names with a timestamp.

## Environment
- Use the conda environment scrna-2026 (versions pinned in environment.yml). Ask me before installing packages.
- Run scripts as: python scripts/<name>.py 2>&1 | tee logs/$(date +%Y%m%d-%H%M%S)-<name>.log

## Reproducibility
- Fix seed=20261010 for every random process and record it in the result table metadata.
- Every number in the results must be regenerable by a script in scripts/; no hand calculation in chat.
- When an analysis parameter changes, update the parameter table and the reason in docs/params.md.

## Statistics
- Differential expression: Wilcoxon test, BH correction, padj < 0.05 and |log2FC| > 1.
- Sample information comes from data/raw/metadata.csv; keep group names as they are.

## Long jobs
- Commands expected to run longer than 5 minutes run in the background with nohup and write a log; report progress by reading the log.

<!-- Maintainer note: this HTML comment does not enter Claude's context -->
See @docs/params.md for current parameters.

Files are concatenated

All discovered files are concatenated from the filesystem root down to the launch directory; none overrides another. When two rules conflict, Claude may pick either, so do not write contradictory requirements at different levels.

@ imports

@path resolves relative to the file containing it, up to 4 levels deep. Escape spaces with backslashes; a quoted path is not imported; a path inside backticks is not imported. Imported files all load at launch, so imports do not save context. A project file that imports a path outside the project triggers a one-time approval dialog.

Length

The official advice is under 200 lines per file; longer files trigger a warning at startup and in /status, and files over 4 MiB are skipped. Move rules that apply to only some directories into subdirectory CLAUDE.md files or .claude/rules/. HTML comments <!-- --> do not enter context and can hold notes for human maintainers.

Confirm it loaded

Run /context and look under Memory files for files loaded at launch; subdirectory CLAUDE.md files are not listed there, and a Loaded line appears in the terminal when they load. /memory opens the files for editing. /init drafts a file from your code, and only proposes edits when a file already exists.

After compaction

After /compact, the project-root CLAUDE.md and unscoped rules are re-injected from disk; subdirectory CLAUDE.md files and path-scoped rules return only when a related file is read or written again; requirements stated only in chat get summarized away. Put requirements that must always apply in the root CLAUDE.md.

Coexisting with AGENTS.md

When a directory has both CLAUDE.md and AGENTS.md, Claude reads only CLAUDE.md by default (reading AGENTS.md directly needs 2.1.277 or later). Groups that also use Codex can put a line @AGENTS.md in CLAUDE.md and maintain one set of rules.

LevelLocationWhen it loadsWhat goes in it
OrganizationmacOS /Library/Application Support/ClaudeCode/CLAUDE.md; Linux /etc/claude-code/CLAUDE.mdAt launchRules distributed by admins
User~/.claude/CLAUDE.mdAt launch, every projectPersonal habits: reply language, code style
Project./CLAUDE.md or ./.claude/CLAUDE.mdAt launchDirectory conventions, run commands, statistics conventions; shared via the repository
Local./CLAUDE.local.md (add to .gitignore)At launch, after CLAUDE.md in the same directoryYour own paths and test data
Parent directoriesCLAUDE.md in every directory above the launch directoryAt launchConventions shared by several projects
SubdirectoriesCLAUDE.md below the launch directoryWhen Claude reads or writes a file in that subdirectoryRules for one submodule
Path rules.claude/rules/*.md with paths in frontmatterWhen a matching file is read or writtenRules only for R scripts, only for notebooks, and so on
Source: official How Claude remembers your project.

Step 4

The permission mode decides which actions run without asking you; rules in settings.json allow or block specific actions on top of the mode. Deny rules apply in every mode, including bypassPermissions.

Shared .claude/settings.json for a research group (committed; validated with claude doctor on this page)json
{
  "$schema": "https://json.schemastore.org/claude-code-settings.json",
  "permissions": {
    "defaultMode": "acceptEdits",
    "allow": [
      "Bash(python scripts/*)",
      "Bash(Rscript scripts/*)",
      "Bash(git diff *)",
      "Bash(git status)"
    ],
    "ask": [
      "Bash(git push *)",
      "Bash(pip install *)",
      "Bash(conda install *)"
    ],
    "deny": [
      "Edit(data/raw/**)",
      "Bash(rm -rf *)",
      "Read(./.env)"
    ]
  },
  "env": { "BASH_DEFAULT_TIMEOUT_MS": "600000" },
  "cleanupPeriodDays": 365
}
Back up raw data protection with filesystem permissionsbash
# Make raw data read-only at the OS level (tested on this page: Python appends then raise
# PermissionError and rm -f returns Permission denied)
chmod -R a-w data/raw
# Lift it yourself when raw data must be updated
chmod -R u+w data/raw

Evaluation order

Deny first, then ask, then allow; the first match wins regardless of how specific the rule is. A deny on Bash(git *) blocks an allow on Bash(git status). Lists with the same key in several settings files are merged, not overridden.

Where the wildcard goes

Put * after the subcommand. Bash(git log *) allows only git log; Bash(git *) allows every git subcommand, including git -c, which can run any program. Bash(ls *) does not match lsof; Bash(ls*) does.

Path syntax

In Edit(/data/**), a single leading slash is relative to the project of the settings file; absolute paths are written //home/me/data/** and home paths ~/. A /secrets/** rule in user settings means ~/.claude/secrets. Path rules written as Write(...) or NotebookEdit(...) are accepted but never consulted; write Edit(...) instead.

Deny rules do not reach scripts

Read and Edit rules apply to the built-in file tools and to cat, sed, tee and redirections that Claude Code recognizes, not to open() or write.csv() inside a Python or R script. A .claudeignore file has no effect. The reliable protection for raw data is chmod -R a-w plus a PreToolUse hook that blocks writes.

What overly broad permissions cost

acceptEdits auto-approves rm inside the working directory. Checkpoints (Esc Esc or /rewind) roll back only files Claude changed with its edit tools; files deleted or moved by Bash commands are not tracked. The built-in critical-path protection blocks rm on the root, home and working directory themselves, not on data/ under the working directory.

Values that only work at user level

defaultMode set to auto or bypassPermissions has no effect in the project .claude/settings.json or settings.local.json; put it in ~/.claude/settings.json or pass --permission-mode. Tested on this page: claude doctor does not flag this.

ModeRuns without askingUse in research work
default (shown as Manual)Reads onlyFirst contact with unfamiliar code, sensitive data
acceptEditsReads, file edits, and mkdir, touch, rm, rmdir, mv, cp, sed inside the working directoryIterate and review with git diff; raw data needs separate protection
planFile reads and exploratory commands; no source edits until you approve the planPropose a plan before changing an analysis pipeline; /plan enters it for one prompt
autoNearly everything, reviewed in the background by a separate classifier modelLong tasks with a clear direction; the default for interactive sessions since 2.1.283
dontAskOnly actions already allowed; everything else is deniedUnattended claude -p batches and CI
bypassPermissionsEverything except deny rules, ask rules and critical-path removalsOnly in containers or VMs without network access; refuses to start as root or under sudo
Source: official Choose a permission mode. Shift+Tab cycles modes in a session; bypassPermissions joins the cycle only when enabled by a launch flag.

Commands

Commands from older tutorials that no longer work: claude config set was deprecated in 1.0.7 and removed in 2.0.0; edit settings.json or use /config instead (tested on this page: 2.1.296 lists no config subcommand). The # prefix for quick memory entries was removed in 2.0.70. /vim was removed in 2.1.92; set Editor mode in /config. npm update -g may stay on an old version; upgrade with npm install -g @anthropic-ai/claude-code@latest.

Command or keyWhat it doesNotes
/initDraft a project CLAUDE.mdOnly proposes edits when a file already exists
/contextShow context usage as a gridSee how much Memory files, MCP tools and the conversation take
/compact [focus]Summarize the conversation to free contextAdd a focus, for example /compact keep the parameter table and the last error
/clear [name]Start a new conversationFree; the old one is available via /resume
/resume, /renameResume and name sessionsName before /clear so you can resume by name later
/rewind (Esc Esc)Return to an earlier message and optionally restore codeDoes not undo changes made by Bash commands
/model, /effortSwitch model and reasoning effort/model saves the choice as the default for new sessions
/permissions, /config, /statusManage rules and settings; show account and gateway/status is the first step when debugging login or gateway issues
/usageUsage and cost/cost and /stats are aliases
/memory, /hooks, /mcp, /skillsManage each extension typeThe /agents wizard was removed in 2.1.198; ask Claude to create subagents or edit .claude/agents/
/export [file]Export the conversation as plain textFor keeping a record of the work
/doctorIn-session setup checkup/doctor prompt-audit checks CLAUDE.md for conflicts and stale content
Shift+TabCycle permission modesAlt+M in some Windows terminals
EscInterrupt the current response or tool callWork done so far is kept
Ctrl+OOpen the full transcript viewShows each tool call and the model used
Ctrl+BMove a running command or subagent to the backgroundPress twice in tmux
Ctrl+GEdit the prompt or plan in an external editorUseful for long instructions
! prefixRun a shell command directly and add its output to the conversationFor example !nvidia-smi
@ prefixReference a file pathWith autocomplete
\ + Enter or Ctrl+JInsert a newlineWorks in every terminal
Sources: official Commands and Interactive mode docs, checked against 2.1.296.

Extensions

Each has a different job: a subagent completes one kind of task in its own context; a hook runs a shell command at a fixed point, independent of the model's judgment; a skill is a procedure loaded on demand; MCP connects external tools and data.

.claude/agents/stats-reviewer.md (statistics review subagent)markdown
---
name: stats-reviewer
description: Reviews analysis scripts and result tables for statistical errors. Use after an analysis script changes or before results go into a figure or manuscript.
tools: Read, Grep, Glob, Bash
model: sonnet
---

You are a statistical methods reviewer. Check that sample sizes and groups match data/raw/metadata.csv,
that multiple comparisons are corrected, that random seeds are fixed, and that every number in the result
tables can be regenerated by a script in scripts/. Report problems with evidence only; do not modify files.
.claude/hooks/protect-raw.sh (tested on this page: writes to data/raw return 2 and are blocked, writes to results return 0)bash
#!/bin/bash
# .claude/hooks/protect-raw.sh: block Edit/Write calls that target data/raw/
# Exit code 2 blocks the call; stderr is sent back to Claude as the reason
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
FILE_PATH="${FILE_PATH//\\//}"
if [[ "$FILE_PATH" == *"/data/raw/"* ]]; then
  echo "Blocked: $FILE_PATH is raw data (read-only). Write to data/processed/ or results/." >&2
  exit 2
fi
exit 0
Register the hook in .claude/settings.json (chmod +x the script first)json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-raw.sh" }
        ]
      }
    ]
  }
}
.claude/skills/run-analysis/SKILL.md (invoke with /run-analysis 03_de.py)markdown
---
name: run-analysis
description: Run one analysis script reproducibly and log the environment. Use when the user asks to run or rerun an analysis.
disable-model-invocation: true
---

1. Record `git rev-parse --short HEAD`, `python --version` and `conda env export --no-builds` in logs/.
2. Run `python scripts/$ARGUMENTS 2>&1 | tee logs/$(date +%Y%m%d-%H%M%S)-run.log`.
3. Report output file paths and key numbers. Do not modify data/raw/.
MCP and format checksbash
# Add an MCP server (local scope by default: only you, only this project; stored in ~/.claude.json)
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp
claude mcp add my-db -e DB_URL=postgres://... -- npx -y some-db-mcp
# Share with your group: written to .mcp.json at the project root (teammates approve it on first run)
claude mcp add --scope project zotero -- npx -y zotero-mcp
claude mcp list            # unapproved .mcp.json servers show as Pending approval
# Check agent and skill file format (tested on this page: a missing description only gives a warning,
# but the agent is skipped at runtime)
claude plugin validate .claude/agents

Subagent files skipped silently

If the frontmatter lacks name or description, the YAML does not parse, or the opening --- is not on the first line, the file does not load and the session says nothing. Check with claude plugin validate .claude/agents, then read the log from claude --debug. A subagent's system prompt is only the file body plus environment details such as the working directory; it does not see the main conversation, so put the background it needs in the body or in the delegation request.

Hooks are more reliable than CLAUDE.md

A PreToolUse hook that returns deny or exits with code 2 blocks the call even in bypassPermissions mode. A hook that returns allow cannot override a deny rule in settings. PostToolUse runs after the tool and cannot undo it. Command hooks time out after 10 minutes by default.

MCP config is not in settings.json

Personal MCP servers are stored in ~/.claude.json; shared project servers in .mcp.json at the project root. Prefer command-line tools (gh, aws) when they can do the job, since MCP servers take context; disable unused servers with /mcp. Behind a gateway set with ANTHROPIC_BASE_URL, MCP tool search is off by default and every tool definition enters context.

Skills versus CLAUDE.md

Facts that must hold in every session go in CLAUDE.md; multi-step procedures go in a skill, which loads only when invoked. disable-model-invocation: true means only you can invoke it with /name. After compaction each skill keeps at most its first 5,000 tokens, so put the key steps near the top of SKILL.md.

Scripts and sessions

claude -p batches and session resumebash
# One run, result as JSON so a script can read result, session_id and total_cost_usd
claude -p "Read results/03_de_genes.csv and list the 20 genes with the smallest padj and their log2FC" \
  --output-format json --permission-mode dontAsk --allowedTools "Read" \
  --max-turns 5 --max-budget-usd 0.50 < /dev/null > logs/summary.json
jq -r '.result' logs/summary.json

# Batch: one independent run per sample; a non-zero exit code marks failure
for s in S01 S02 S03; do
  claude -p "Check cell count, gene count and mitochondrial fraction in data/processed/$s.h5ad and write a QC summary" \
    --permission-mode dontAsk --allowedTools "Read" "Bash(python scripts/qc_summary.py *)" \
    < /dev/null > logs/qc-$s.md || echo "$s failed" >> logs/failed.txt
done

# Resume sessions
claude --continue                 # most recent interactive session in this directory
claude --resume                   # open the session picker (Ctrl+A shows every project on this machine)
claude --resume de-analysis       # resume by name (name it in-session with /rename de-analysis)
claude -p --resume <session-id> "Summarize which parameters changed" --output-format json | jq -r '.result'

Run interactively once in the directory first

Tested on this page: claude -p in an untrusted directory prints Ignoring 4 permissions.allow entries from .claude/settings.json: this workspace has not been trusted. None of the project allow rules apply, while env from the same settings file still applies. In a fresh clone or a new directory on a cluster, run claude once and accept the trust dialog.

stdin and exit codes

When stdin is not a terminal, claude -p waits 3 seconds and prints Warning: no stdin data received in 3s; add < /dev/null in scripts. When not logged in, stdout reads Not logged in · Please run /login and the exit code is 1 (tested on this page). In -p mode, settings files that fail validation are ignored silently, so run claude doctor before a batch.

-p sessions are not in the picker

Sessions created by claude -p do not appear in the claude --resume picker, and claude --continue skips them; continue one with the session_id from --output-format json and claude --resume <id>. When resuming, pass launch flags such as --mcp-config, --add-dir and --settings again.

Starting permission mode for -p

The starting mode of claude -p depends on the version and on whether feature flags are fetched; it can be default or auto. Pass --permission-mode dontAsk with an --allowedTools allowlist in scripts for predictable results.

Context

  1. 01

    Check usage first

    /context shows how much the system prompt, Memory files, MCP tools and the conversation each take. If a large share is used at startup, trim CLAUDE.md, skills or MCP servers.

  2. 02

    /clear when you switch tasks

    Old conversation unrelated to the current task is billed again on every request. Before switching, name the session with /rename, then /clear. /clear costs nothing; /compact reads the whole conversation, so on a large context it is itself a large request.

  3. 03

    Say what to keep when compacting

    For example, /compact keep the parameter table, the last error and the unfinished steps. You can also add a # Compact instructions section to CLAUDE.md. /autocompact 300000 makes automatic compaction trigger earlier.

  4. 04

    Do not read whole data files

    Have Claude inspect structure with head, wc -l, pandas nrows or df.info() instead of reading a whole CSV. A very large output can trigger Autocompact is thrashing: context refills right after compaction and Claude Code stops retrying. Read in chunks, or hand large-file processing to a subagent so it happens in a separate context.

  5. 05

    Command output limits

    By default only about 30,000 characters of Bash output enter context inline; the rest is saved to a file that Claude reads on demand. Failed commands keep a head-and-tail excerpt of about 10,000 characters. grep or tail long logs before handing them to Claude.

Research practice

Research work runs long, raw data cannot be regenerated, and results must be reproducible. The practices below address these three points.

How to start long jobsbash
# Have Claude start long jobs this way: the job is independent of Claude's process and logs to disk
nohup python scripts/05_train.py --config configs/run3.yaml \
  > logs/run3-$(date +%Y%m%d-%H%M).log 2>&1 &
echo $! > logs/run3.pid
# On HPC, submit to the scheduler instead of running on the login node
sbatch scripts/05_train.slurm
# Then have Claude read tail -n 50 logs/run3-*.log to report progress instead of waiting in the foreground
  1. 01

    Confirm the approach in plan mode

    Before changing an analysis pipeline, press Shift+Tab into plan mode or prefix the prompt with /plan. Claude only reads files and writes a plan; edit the plan in your editor with Ctrl+G and approve it before execution. The plan file is re-injected from disk after compaction, so it works as the outline of a long task.

  2. 02

    Keep long jobs outside Claude's process

    Foreground Bash commands time out after 2 minutes by default, 10 minutes at most, and then move to the background. Background commands in a local interactive session have no time limit, but in claude -p they stop after 10 minutes by default and 2 hours at most. Start model training or molecular simulations with nohup or sbatch, write logs to files, and have Claude read the logs to report progress.

  3. 03

    Activate the environment before starting claude

    Each Bash command runs in a separate process and variables set with export do not carry over to the next command, so a conda activate that Claude runs mid-session only lasts for that one command. Run conda activate first, then claude; for extra variables, point CLAUDE_ENV_FILE at a setup script.

  4. 04

    Keep a record of the work

    Transcripts are stored as JSONL under ~/.claude/projects/<directory name>/ and deleted silently after 30 days by default. For projects that need an archive, raise cleanupPeriodDays in settings.json (for example 365), export key sessions with /export, and commit them with the run logs in logs/.

  5. 05

    Make results reproducible

    In CLAUDE.md, require that every number comes from a script, that random seeds are fixed, and that parameter changes go into a parameter table. Fix the run procedure in a skill (record the git commit and conda env export). Before delivery, have a subagent such as stats-reviewer review the work separately.

  6. 06

    Control cost

    Configure the status line to show context usage and cost (/statusline). Use Sonnet day to day and switch to Opus for complex planning; give simple subagents model: haiku. Start a new session for each independent question, since a long session bills even a one-line question against the whole context. Add --max-budget-usd to batches.

Chinese community

These items come from hands-on posts on CSDN and the Alibaba Cloud developer community. Each was checked against the official docs or tests on this page, with its conditions and corrections noted.

First run stuck at Unable to connect to Anthropic services

Three authors reported independently (CSDN, March to June 2026): with a relay, the first run fails with Failed to connect to api.anthropic.com: ERR_BAD_REQUEST, and adding "hasCompletedOnboarding": true to ~/.claude.json gets past it. The official docs say the first-run wizard probes api.anthropic.com and platform.claude.com. Correction: add the key with an editor instead of overwriting the file with cat > ~/.claude.json, which also holds project trust, OAuth and personal MCP servers; the key has no effect in settings.json, and claude doctor does not flag it there (tested on this page).

requires git-bash error

A CSDN author hit Claude Code on Windows requires git-bash and fixed it by setting CLAUDE_CODE_GIT_BASH_PATH. Current versions fall back to PowerShell without Git for Windows; the message now reads requires either Git for Windows (for bash) or PowerShell and appears only when neither is available.

Third-party model returns thinking type should be enabled or disabled

The cause given in an Alibaba Cloud community post (the upstream does not support adaptive thinking) matches the official troubleshooting table, but the post writes the variable in lowercase as claude_code_disable_adaptive_thinking. Environment variables are case-sensitive; the name is CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING, and the official docs say it only affects Opus 4.6 and Sonnet 4.6.

Lab servers without root

A CSDN post installs Node with nvm and then Claude Code with npm, which works without root. The native install script already installs to ~/.local/bin and needs neither Node nor root. The same post points ANTHROPIC_DEFAULT_HAIKU_MODEL at the retired claude-3-5-haiku; that model also runs background tasks, so use a model the gateway currently serves.

Putting "ask me before deleting" in CLAUDE.md

Many tutorials put file deletion and git push as hard rules in CLAUDE.md. The official docs say CLAUDE.md is context rather than enforced configuration, and GitHub #2544 records such rules being ignored. Write these as ask or deny rules in settings.json, or as a PreToolUse hook.

Errors

Debug order: claude --version to confirm the version; claude doctor to check the install and settings files; /status in a session to confirm the account, gateway and loaded settings files; if still unclear, start with claude --debug and read the log under ~/.claude/debug/; if you suspect your own configuration, compare with claude --safe-mode.

Error messageCauseFix
command not found: claude / 'claude' is not recognizedThe install directory is not on PATH, or you are in a terminal opened before the installOpen a new terminal; add ~/.local/bin (%USERPROFILE%\.local\bin on Windows) to PATH
syntax error near unexpected token '<'The install URL returned a web page instead of the script, common with network routing or regional restrictionsRetry later or use brew / winget; App unavailable in region in the output means your region is not supported
curl: (22) ... error: 403A proxy or firewall blocks the download, or a regional restrictionCheck connectivity to downloads.claude.ai and your proxy settings
Killed (during install on Linux)Out of memoryThe official minimum is 4 GB RAM; free memory or add swap and reinstall
Bus error / oh no: Bun has crashedThe running executable was deleted or truncated, common on NFS-shared homesInstall the binary on local disk and turn off self-updates for central upgrades
OAuth error: Invalid codeThe login code expired or was copied incompletelyRun /login again and paste soon after the browser opens
API Error: 403 Request not allowedSubscription inactive, the Console account lacks the Claude Code role, or proxy interferenceCheck the subscription at claude.ai/settings; ask the Console admin for the Developer or Claude Code role
Not logged in · Please run /loginNo usable credential/login, or set ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN
Unable to connect to API (ECONNREFUSED / ENOTFOUND / ERR_PROXY_TUNNEL)No network route, proxy not set, or a stale ANTHROPIC_BASE_URLTest with curl -I https://api.anthropic.com; check echo $ANTHROPIC_BASE_URL; on WSL check /etc/resolv.conf
You've hit your session limit · resets 3:45pmSubscription allowance used upWait for the reset; check /usage; for a separate Opus or Sonnet limit, switch family with /model
Context limit reached · /compact or /clear to continueConversation plus attachments exceed the context window/compact with a focus; /clear if the old conversation is not needed
Autocompact is thrashingA large file or output refills context right after compactionRead in chunks; hand large files to a subagent; drop large output when compacting
Claude Opus is not available with the Claude Pro planThe plan does not include the model, or the token was not refreshed after an upgrade/model to another model; after an upgrade, /logout then /login
--dangerously-skip-permissions cannot be used with root/sudo privilegesBypass mode run as rootRun as a regular user, or inside the official dev container
Claude Code on Windows requires either Git for Windows (for bash) or PowerShellNeither shell can be foundInstall Git for Windows, or set CLAUDE_CODE_GIT_BASH_PATH
Sources: official Troubleshoot installation and login, Error reference, Choose a permission mode; GitHub issues.

Hand it to an agent

Example instruction: "This is my analysis repository. First browse the code and data/README.md read-only, write a CLAUDE.md and .claude/settings.json following the directory conventions on this page, and make data/raw read-only. Then rerun the differential expression analysis from raw counts using the pipeline in scripts/, run long steps in the background with logs, and deliver the result tables, figures and a record of parameters and environment."

Steps the agent takes: clones the repository in an isolated cloud computer and builds the environment from environment.yml; writes a plan first, then generates CLAUDE.md and the permission configuration; rents a GPU automatically when a step needs one, runs long steps in the background and reports from the logs; reviews the results adversarially, checking sample groups, multiple-comparison correction and random seeds.

Output files: CLAUDE.md, .claude/settings.json, a run log for each step, tables and figures in results/, and a reproduction note recording the git commit and conda environment. The task continues after you close your machine.

What you still need to check: whether the statistical method fits your experimental design, whether groups and covariates match the sample information, and whether thresholds and parameters match your group's earlier analyses.

Checklist

  • claude --version meets the version required by the features you rely on; on clusters the binary is on local disk
  • /status shows the account or gateway you expect, with no stale ANTHROPIC_API_KEY
  • The project root has a CLAUDE.md under 200 lines with directory conventions, run commands, random seeds and statistics conventions
  • data/raw is chmod -R a-w, and settings.json has an Edit(data/raw/**) deny rule
  • Actions that need confirmation (git push, installing dependencies) are ask rules; bypassPermissions is not used
  • cleanupPeriodDays is raised, a logs/ directory exists, and key sessions are saved with /export
  • Batch scripts use --permission-mode dontAsk, an --allowedTools allowlist, < /dev/null and --max-budget-usd, and claude has been run interactively once in that directory
  • Long jobs start with nohup or sbatch, and Claude only reads their logs

Sources

FAQ

Can I use Claude Code on the free plan?

No. The official docs say Claude Code requires a Pro, Max, Team or Enterprise subscription or a Console account; the free claude.ai plan does not include Claude Code. For pay-as-you-go, use a Console API key.

How much does Claude Code cost, and is a subscription or the API cheaper?

Pro is $20 billed monthly ($17/month billed annually) and Max starts at $100 per month; on the API, Sonnet 5.5 costs $2 input and $10 output per million tokens. Official figures put the enterprise average at about $13 per active day. If you use it several hours every day, a subscription is cheaper; for occasional use or scripts, use the API.

How do I use Claude Code in China?

Operationally there are three ways in: sign in with an official account; use a gateway by setting ANTHROPIC_BASE_URL and ANTHROPIC_AUTH_TOKEN in the env block of ~/.claude/settings.json; or switch to a domestic model. For cost, model source and risk of each approach, see How to use Codex and Claude Code in China. Only HTTP proxies work; Claude Code does not support SOCKS.

Why does Claude ignore the rules in my CLAUDE.md?

CLAUDE.md enters context as a user message; it is not enforced configuration. Use /context to confirm the file loaded, then look for contradictory requirements across levels. Rewrite limits that must hold as ask or deny rules in settings.json, or as a PreToolUse hook.

Why doesn't Claude Code ask me before every step anymore?

Since 2.1.283, interactive terminal and VS Code sessions with no configured permission mode start in auto mode, where a classifier model reviews actions. To review every action again, press Shift+Tab to Manual, or set permissions.defaultMode to default in ~/.claude/settings.json.

How do I continue the last conversation after closing the terminal?

Run claude --continue in the same directory for the most recent session, or claude --resume for the session picker. Sessions created by claude -p are not in the picker; resume them with claude --resume <id> using their session_id. Transcripts are kept for 30 days by default.

Hand long-running research computation to Scientify

The scientific agent runs in an isolated cloud computer with molecular simulation, bioinformatics and AI computing environments preinstalled. It rents a GPU automatically when a task needs one, keeps running after you close your machine, and keeps code, parameters, logs and results in the workspace. Usage costs about 30% of the standard API price for the same models, and new users get $5 of free credit.