Loading...
    • 开发者指南
    • API 参考
    • MCP
    • 资源
    • 更新日志
    Search...
    ⌘K
    入门
    Claude 简介快速开始
    模型与定价
    模型概览选择模型Claude 4.6 新特性迁移指南模型弃用定价
    使用 Claude 构建
    功能概览使用 Messages API处理停止原因提示词最佳实践
    上下文管理
    上下文窗口压缩上下文编辑
    能力
    提示缓存扩展思考自适应思考推理力度流式消息批量处理引用多语言支持Token 计数嵌入视觉PDF 支持Files API搜索结果结构化输出
    工具
    概览如何实现工具使用细粒度工具流式传输Bash 工具代码执行工具程序化工具调用计算机使用工具文本编辑器工具网页抓取工具网页搜索工具记忆工具工具搜索工具
    Agent Skills
    概览快速开始最佳实践企业级 Skills通过 API 使用 Skills
    Agent SDK
    概览快速开始TypeScript SDKTypeScript V2(预览版)Python SDK迁移指南
    API 中的 MCP
    MCP 连接器远程 MCP 服务器
    第三方平台上的 Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    提示工程
    概览提示词生成器使用提示词模板提示词优化器清晰直接使用示例(多样本提示)让 Claude 思考(思维链)使用 XML 标签赋予 Claude 角色(系统提示词)链式复杂提示长上下文技巧扩展思考技巧
    测试与评估
    定义成功标准开发测试用例使用评估工具降低延迟
    加强安全护栏
    减少幻觉提高输出一致性防范越狱攻击流式拒绝减少提示词泄露保持 Claude 角色设定
    管理与监控
    Admin API 概览数据驻留工作空间用量与成本 APIClaude Code Analytics API零数据留存
    Console
    Log in
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...

    Solutions

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

    Partners

    • Amazon Bedrock
    • Google Cloud's Vertex AI

    Learn

    • Blog
    • Catalog
    • 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
    • Catalog
    • 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 工具

    Bash 工具使 Claude 能够在持久化的 bash 会话中执行 shell 命令,支持系统操作、脚本执行和命令行自动化。

    概述

    Bash 工具为 Claude 提供:

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

    模型兼容性

    模型工具版本
    Claude 4 模型和 Sonnet 3.7(已弃用)bash_20250124

    旧版工具不保证与新模型向后兼容。请始终使用与您的模型版本对应的工具版本。

    使用场景

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

    快速开始

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

    工作原理

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

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

    参数

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

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

    示例:多步骤自动化

    Claude 可以链接命令来完成复杂任务:

    # 用户请求
    "Install the requests library and create a simple Python script that fetches a joke from an API, then run it."
    
    # Claude 的工具使用:
    # 1. 安装软件包
    {"command": "pip install requests"}
    
    # 2. 创建脚本
    {"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. 运行脚本
    {"command": "python fetch_joke.py"}

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


    实现 bash 工具

    Bash 工具作为无模式工具实现。使用此工具时,您不需要像其他工具那样提供输入模式;模式内置于 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):
          # Send command to bash
          self.process.stdin.write(command + '\n')
          self.process.stdin.flush()
          
          # Capture output with timeout
          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)
              
              # Return result to Claude
              tool_result = {
                  "type": "tool_result",
                  "tool_use_id": content.id,
                  "content": result
              }
    4. 4

      实施安全措施

      添加验证和限制:

      def validate_command(command):
          # Block dangerous commands
          dangerous_patterns = ['rm -rf /', 'format', ':(){:|:&};:']
          for pattern in dangerous_patterns:
              if pattern in command:
                  return False, f"Command contains dangerous pattern: {pattern}"
          
          # Add more validation as needed
          return True, None

    处理错误

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

    遵循实现最佳实践

    安全性

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

    • 在隔离环境中运行(Docker/VM)
    • 实施命令过滤和白名单
    • 设置资源限制(CPU、内存、磁盘)
    • 记录所有已执行的命令

    关键建议

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

    定价

    The bash tool adds 245 input tokens to your API calls.

    Additional tokens are consumed by:

    • Command outputs (stdout/stderr)
    • Error messages
    • Large file contents

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

    常见模式

    开发工作流

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

    文件操作

    • 处理数据: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 应用程序:仅限命令行
    • 会话范围:在对话中保持,API 调用之间丢失
    • 输出限制:大量输出可能会被截断
    • 不支持流式传输:结果在完成后返回

    与其他工具结合使用

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

    后续步骤

    工具使用概述

    了解如何在 Claude 中使用工具

    文本编辑器工具

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

    Was this page helpful?

    • 实现 bash 工具