跳到主要内容

文件操作工具

文件操作是 Claude Code 最基础也最常用的能力。提供了 5 个核心文件工具。

BashTool

执行 Shell 命令,是 Claude Code 中功能最强大的工具。

// 输入 Schema
{
command: string; // 要执行的命令
timeout?: number; // 超时时间(毫秒,最大 600000)
description?: string; // 命令描述
}

特点

  • 工作目录在命令间保持不变
  • Shell 状态(环境变量、别名)不跨命令保持
  • 支持后台运行(run_in_background
  • 自动继承用户的 shell profile(bash/zsh)
  • 命令输出实时流式展示

安全限制

  • 检测并警告危险命令(rm -rfgit reset --hard 等)
  • 沙盒模式限制特定操作
  • 超时保护,默认 2 分钟

FileReadTool

读取本地文件内容,支持多种文件格式。

{
file_path: string; // 绝对路径
offset?: number; // 起始行号
limit?: number; // 读取行数(默认 2000)
pages?: string; // PDF 页码范围
}

支持的格式

  • 文本文件(代码、配置、日志等)
  • 图片(PNG、JPG 等,以视觉方式呈现给 Claude)
  • PDF(支持分页读取,每次最多 20 页)
  • Jupyter Notebook(.ipynb,含代码和输出)

输出格式

使用 cat -n 格式,带行号:

1  import React from 'react';
2 import { Box, Text } from 'ink';
3
4 export function App() {

FileWriteTool

创建或完整覆写文件

{
file_path: string; // 绝对路径
content: string; // 文件内容
}

使用规则

  • 覆写已有文件前必须先用 Read 读取
  • 优先使用 Edit 修改现有文件(只发差异)
  • 仅在需要新建文件或完整重写时使用

FileEditTool

精确字符串替换编辑,Claude Code 最常用的编辑方式。

{
file_path: string; // 绝对路径
old_string: string; // 要替换的原始文本
new_string: string; // 替换后的文本
replace_all?: boolean; // 是否全局替换(默认 false)
}

设计原则

  • 精确匹配old_string 必须在文件中唯一匹配
  • 最小化变更 — 只传递差异,不传完整文件
  • 保留格式 — 严格保持原始缩进和格式
  • 如果 old_string 不唯一,需要提供更多上下文使其唯一

NotebookEditTool

编辑 Jupyter Notebook 单元格

{
notebook_path: string; // Notebook 文件路径
cell_index: number; // 单元格索引
new_source: string; // 新的单元格内容
cell_type?: string; // 单元格类型(code/markdown)
}

工具选择策略

Claude Code 在系统提示词中明确规定了工具选择的优先级:

操作推荐工具不推荐
读取文件FileReadToolcat, head, tail
编辑文件FileEditToolsed, awk
创建文件FileWriteToolecho >, cat <<EOF
搜索文件名GlobToolfind, ls
搜索内容GrepToolgrep, rg
系统命令BashTool