Was this page helpful?
此功能符合「Zero Data Retention」(零資料保留),即 ZDR 的資格。當您的組織具有 ZDR 安排時,透過此功能傳送的資料在 API 回應返回後不會被儲存。
Bash 工具讓 Claude 能夠在持久性的 bash 工作階段中執行 shell 命令,從而實現系統操作、腳本執行和命令列自動化。Shell 存取是一項基礎的代理能力。在 Terminal-Bench 2.0(一個使用純 shell 驗證來評估真實世界終端機任務的基準測試)中,Claude 在具備持久性 bash 工作階段存取權限時展現出顯著的效能提升。
Bash 工具為 Claude 提供:
如需模型支援資訊,請參閱工具參考。
Bash 工具維持一個持久性工作階段:
| 參數 | 必填 | 說明 |
|---|---|---|
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 工具是以無結構描述(schema-less)工具的形式實作。使用此工具時,您不需要像其他工具一樣提供輸入結構描述;該結構描述已內建於 Claude 的模型中,且無法修改。
實作 bash 工具時,請處理各種錯誤情境:
Bash 工具提供直接的系統存取權限。請實作以下基本安全措施:
ulimit 設定資源限制sudo、rm -rf 等)bash 工具會為您的 API 呼叫增加 245 個輸入 token。
以下項目會消耗額外的 token:
如需完整的定價詳情,請參閱工具使用定價。
pytest && coverage reportnpm install && npm run buildgit status && git add . && git commit -m "message"在長時間執行的代理工作流程中,Git 可作為結構化的復原機制,而不僅僅是儲存變更的方式:
git log 並搭配進度檔案,以了解已完成的工作和接下來的步驟。git checkout 還原到最後一個良好的提交,而不是嘗試除錯損壞的狀態。wc -l *.csv && ls -lh *.csvfind . -name "*.py" | xargs grep "pattern"tar -czf backup.tar.gz ./datadf -h && free -mps aux | grep pythonexport PATH=$PATH:/new/path && echo $PATHvim、less 或密碼提示Bash 工具與文字編輯器和其他工具結合使用時最為強大。
如果您同時使用程式碼執行工具,Claude 將可存取兩個獨立的執行環境:您的本機 bash 工作階段和 Anthropic 的沙箱容器。兩者之間不共用狀態。如需提示 Claude 區分不同環境的指引,請參閱將程式碼執行與其他執行工具搭配使用。
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 環境
建立一個 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()處理命令執行
建立一個函式來執行命令並擷取輸出:
def execute_command(self, command):
# 傳送指令至 bash
self.process.stdin.write(command + "\n")
self.process.stdin.flush()
# 擷取輸出並設定逾時
output = self._read_output(timeout=10)
return output
處理 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,
}實作安全措施
新增驗證和限制。使用允許清單(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 就不會解譯該字串。