Claude Platform Docs
  • 消息
  • 托管智能体
  • 管理

Search...
⌘K
第一步
Claude 简介快速入门
使用 Claude 构建
功能概览使用 Messages API停止原因与回退拒绝与回退回退额度
模型能力
扩展思考自适应思考努力程度任务预算(测试版)快速模式(研究预览)结构化输出引用流式传输消息批量处理搜索结果流式传输拒绝多语言支持嵌入
工具
概览工具使用的工作原理教程:构建使用工具的智能体定义工具处理工具调用并行工具使用工具运行器(SDK)严格工具使用工具使用与提示缓存服务器工具故障排除网页搜索工具网页抓取工具代码执行工具顾问工具记忆工具Bash 工具计算机使用工具文本编辑器工具
工具基础设施
工具参考管理工具上下文工具组合工具搜索编程式工具调用细粒度工具流式传输
上下文管理
上下文窗口压缩上下文编辑提示缓存对话中系统消息构建编排模式缓存诊断(测试版)令牌计数
处理文件
Files APIPDF 支持图像与视觉
技能
概览快速入门最佳实践企业技能API 中的技能
MCP
远程 MCP 服务器MCP 连接器
云平台上的 Claude
Amazon BedrockAmazon Bedrock(旧版)AWS 上的 Claude PlatformMicrosoft FoundryVertex AI

Log in
Bash 工具
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Claude Platform Docs

Solutions

  • AI agents
  • Code modernization
  • Coding
  • Customer support
  • Education
  • Financial services
  • Government
  • Life sciences

Partners

  • Claude on AWS
  • Claude on Google Cloud

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Company

  • Anthropic
  • Careers
  • Economic Futures
  • Research
  • News
  • Responsible Scaling Policy
  • Security and compliance
  • Transparency

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Help and security

  • Availability
  • Status
  • Support
  • Discord

Terms and policies

  • Privacy policy
  • Responsible disclosure policy
  • Terms of service: Commercial
  • Terms of service: Consumer
  • Usage policy
消息/工具

Bash 工具



此功能符合零数据保留(ZDR)的条件。当您的组织签订了 ZDR 协议时,通过此功能发送的数据在 API 响应返回后不会被存储。

Bash 工具使 Claude 能够在持久化的 bash 会话中执行 shell 命令,从而实现系统操作、脚本执行和命令行自动化。Shell 访问是一项基础性的智能体能力。在 Terminal-Bench 2.0(一个使用纯 shell 验证来评估真实终端任务的基准测试)中,Claude 在拥有持久化 bash 会话访问权限时表现出显著的性能提升。

概述

Bash 工具为 Claude 提供:

  • 保持状态的持久化 bash 会话
  • 运行任何 shell 命令的能力
  • 访问环境变量和工作目录
  • 命令链式调用和脚本编写能力

有关模型支持情况,请参阅工具参考。

使用场景

  • 开发工作流: 运行构建命令、测试和开发工具
  • 系统自动化: 执行脚本、管理文件、自动化任务
  • 数据处理: 处理文件、运行分析脚本、管理数据集
  • 环境配置: 安装软件包、配置环境

快速开始

import anthropic

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-opus-4-8",
    max_tokens=1024,
    tools=[{"type": "bash_20250124", "name": "bash"}],
    messages=[
        {"role": "user", "content": "List all Python files in the current directory."}
    ],
)

print(response)

工作原理

Bash 工具维护一个持久化会话:

  1. Claude 确定要运行的命令
  2. 您在 bash shell 中执行该命令
  3. 将输出(stdout 和 stderr)返回给 Claude
  4. 会话状态在命令之间保持(环境变量、工作目录)

参数

参数必需描述
command是*要运行的 bash 命令
restart否设置为 true 以重启 bash 会话

*除非使用 restart,否则为必需

示例:多步骤自动化

Claude 可以链式调用命令来完成复杂任务:

User request:
"Install the requests library and create a simple Python script that
fetches a joke from an API, then run it."

Claude's tool uses:
1. Install package
   {"command": "pip install requests"}

2. Create script
   {"command": "cat > fetch_joke.py << 'EOF'\nimport requests\nresponse = requests.get('https://official-joke-api.appspot.com/random_joke')\njoke = response.json()\nprint(f\"Setup: {joke['setup']}\")\nprint(f\"Punchline: {joke['punchline']}\")\nEOF"}

3. Run script
   {"command": "python fetch_joke.py"}

会话在命令之间保持状态,因此在步骤 2 中创建的文件在步骤 3 中可用。

实现 bash 工具

Bash 工具作为无模式(schema-less)工具实现。使用此工具时,您无需像其他工具那样提供输入模式;该模式已内置于 Claude 的模型中,无法修改。

  1. 1

    设置 bash 环境

    创建一个 Claude 可以与之交互的持久化 bash 会话:

    import subprocess
    import threading
    import queue
    
    
    class BashSession:
        def __init__(self):
            self.process = subprocess.Popen(
                ["/bin/bash"],
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                bufsize=0,
            )
            self.output_queue = queue.Queue()
            self.error_queue = queue.Queue()
            self._start_readers()
  2. 2

    处理命令执行

    创建一个函数来执行命令并捕获输出:

    def execute_command(self, command):
        # 向 bash 发送命令
        self.process.stdin.write(command + "\n")
        self.process.stdin.flush()
    
        # 在超时限制内捕获输出
        output = self._read_output(timeout=10)
        return output
    
  3. 3

    处理 Claude 的工具调用

    从 Claude 的响应中提取并执行命令:

    for content in response.content:
        if content.type == "tool_use" and content.name == "bash":
            if content.input.get("restart"):
                bash_session.restart()
                result = "Bash session restarted"
            else:
                command = content.input.get("command")
                result = bash_session.execute_command(command)
    
            # 将结果返回给 Claude
            tool_result = {
                "type": "tool_result",
                "tool_use_id": content.id,
                "content": result,
            }
  4. 4

    实施安全措施

    添加验证和限制。使用允许列表(allowlist)而非阻止列表(blocklist),因为阻止列表很容易被绕过。拒绝 shell 操作符,以防止链式命令绕过允许列表:

    import shlex
    
    ALLOWED_COMMANDS = {"ls", "cat", "echo", "pwd", "grep", "find", "wc", "head", "tail"}
    SHELL_OPERATORS = {"&&", "||", "|", ";", "&", ">", "<", ">>"}
    
    
    def validate_command(command):
        # 仅允许明确允许列表中的命令
        try:
            tokens = shlex.split(command)
        except ValueError:
            return False, "Could not parse command"
    
        if not tokens:
            return False, "Empty command"
    
        executable = tokens[0]
        if executable not in ALLOWED_COMMANDS:
            return False, f"Command '{executable}' is not in the allowlist"
    
        # 拒绝会串联额外命令的 shell 运算符
        for token in tokens[1:]:
            if token in SHELL_OPERATORS or token.startswith(("$", "`")):
                return False, f"Shell operator '{token}' is not allowed"
    
        return True, None

    此检查是第一道防线。为了实现更强的隔离,请使用 shell=False 运行已验证的命令,并将 shlex.split(command) 作为参数列表传递,这样 shell 就不会解释该字符串。

处理错误

在实现 bash 工具时,请处理各种错误场景:

遵循实现最佳实践

安全性



Bash 工具提供直接的系统访问权限。请实施以下基本安全措施:

  • 在隔离环境(Docker/虚拟机)中运行
  • 实施命令过滤和允许列表
  • 设置资源限制(CPU、内存、磁盘)
  • 记录所有已执行的命令

关键建议

  • 使用 ulimit 设置资源约束
  • 过滤危险命令(sudo、rm -rf 等)
  • 以最小用户权限运行
  • 监控并记录所有命令执行

定价

bash 工具会为您的 API 调用增加 245 个输入令牌。

以下内容会消耗额外的令牌:

  • 命令输出(stdout/stderr)
  • 错误消息
  • 大型文件内容

有关完整的定价详情,请参阅工具使用定价。

常见模式

开发工作流

  • 运行测试:pytest && coverage report
  • 构建项目:npm install && npm run build
  • Git 操作:git status && git add . && git commit -m "message"

基于 Git 的检查点

在长时间运行的智能体工作流中,Git 作为一种结构化的恢复机制,而不仅仅是保存更改的方式:

  • 捕获基线: 在任何智能体工作开始之前,提交当前状态。这是已知良好的起点。
  • 按功能提交: 每个完成的功能都有自己的提交。如果之后出现问题,这些提交可作为回滚点。
  • 在会话开始时重建状态: 结合进度文件读取 git log,以了解已完成的工作和接下来的任务。
  • 失败时回退: 如果工作出现问题,使用 git checkout 回退到最后一个良好的提交,而不是尝试调试损坏的状态。

文件操作

  • 处理数据:wc -l *.csv && ls -lh *.csv
  • 搜索文件:find . -name "*.py" | xargs grep "pattern"
  • 创建备份:tar -czf backup.tar.gz ./data

系统任务

  • 检查资源:df -h && free -m
  • 进程管理:ps aux | grep python
  • 环境配置:export PATH=$PATH:/new/path && echo $PATH

限制

  • 不支持交互式命令: 无法处理 vim、less 或密码提示
  • 不支持 GUI 应用程序: 仅限命令行
  • 会话范围: Bash 会话状态位于客户端。API 是无状态的。您的应用程序负责在多轮对话之间维护 shell 会话。
  • 输出限制: 大型输出可能会被截断
  • 不支持流式传输: 结果在完成后返回

与其他工具结合使用

Bash 工具与文本编辑器和其他工具结合使用时最为强大。



如果您同时使用代码执行工具,Claude 将可以访问两个独立的执行环境:您的本地 bash 会话和 Anthropic 的沙盒容器。这两个环境之间不共享状态。有关如何提示 Claude 区分不同环境的指导,请参阅将代码执行与其他执行工具结合使用。

后续步骤


工具使用概述

了解如何通过 Claude 进行工具使用


文本编辑器工具

使用 Claude 查看和编辑文本文件

Was this page helpful?

  • 概述
  • 使用场景
  • 快速开始
  • 工作原理
  • 参数
  • 示例:多步骤自动化
  • 实现 bash 工具
  • 处理错误
  • 遵循实现最佳实践
  • 安全性
  • 关键建议
  • 定价
  • 常见模式
  • 开发工作流
  • 文件操作
  • 系统任务
  • 限制
  • 与其他工具结合使用
  • 后续步骤