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 思考(CoT)使用 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 可以鏈接命令來完成複雜任務:

    # 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 工具實作為無結構描述工具。使用此工具時,您不需要像其他工具一樣提供輸入結構描述;結構描述內建於 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 工具