Loading...
  • 构建
  • 管理
  • 模型与定价
  • 客户端 SDK
  • API 参考
Search...
⌘K
Log in
Bash 工具
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
  • 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 工具

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

This feature is eligible for Zero Data Retention (ZDR). When your organization has a ZDR arrangement, data sent through this feature is not stored after the API response is returned.

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-7",
    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 可以链接命令来完成复杂任务:

用户请求:
"安装 requests 库并创建一个简单的 Python 脚本,
从 API 获取一个笑话,然后运行它。"

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 环境

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

    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

    实现安全措施

    添加验证和限制。使用允许列表而不是阻止列表,因为阻止列表容易被绕过。拒绝 shell 操作符,以便链接的命令无法绕过允许列表:

    import shlex
    
    ALLOWED_COMMANDS = {"ls", "cat", "echo", "pwd", "grep", "find", "wc", "head", "tail"}
    SHELL_OPERATORS = {"&&", "||", "|", ";", "&", ">", "<", ">>"}
    
    
    def validate_command(command):
        # Allow only commands from an explicit allowlist
        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"
    
        # Reject shell operators that would chain additional commands
        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/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"

基于 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 工具