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

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 命令的能力
  • 訪問環境變量和工作目錄
  • 命令鏈接和腳本編寫功能

有關模型支持,請參閱工具參考。

用例

  • 開發工作流: 運行構建命令、測試和開發工具
  • 系統自動化: 執行腳本、管理文件、自動化任務
  • 數據處理: 處理文件、運行分析腳本、管理數據集
  • 安裝包、配置環境

Was this page helpful?

  • 實現 bash 工具
環境設置:

快速開始

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

處理錯誤

實現 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 查看和編輯文本文件

此檢查是第一道防線。為了更強的隔離,使用 shell=False 運行驗證的命令,並將 shlex.split(command) 作為參數列表傳遞,這樣 shell 永遠不會解釋該字符串。