Bashツールは、Claudeが永続的なbashセッションでシェルコマンドを実行できるようにし、システム操作、スクリプト実行、コマンドライン自動化を可能にします。
Bashツールは、Claudeに以下を提供します:
| モデル | ツールバージョン |
|---|---|
| Claude 4モデルとSonnet 3.7 (廃止予定) | bash_20250124 |
古いツールバージョンは、新しいモデルとの後方互換性が保証されていません。常にモデルバージョンに対応するツールバージョンを使用してください。
Bashツールは永続的なセッションを保持します:
| パラメータ | 必須 | 説明 |
|---|---|---|
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ツールはスキーマレスツールとして実装されています。このツールを使用する場合、他のツールのような入力スキーマを提供する必要はありません。スキーマはClaudeのモデルに組み込まれており、変更することはできません。
Bashツールを実装する場合、様々なエラーシナリオに対応します:
Bashツールは直接的なシステムアクセスを提供します。これらの重要な安全対策を実装してください:
ulimitを使用してリソース制約を設定sudo、rm -rfなど)をフィルタリングThe bash tool adds 245 input tokens to your API calls.
Additional tokens are consumed by:
完全な価格詳細については、ツール使用価格を参照してください。
pytest && coverage reportnpm install && npm run buildgit status && git add . && git commit -m "message"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ツールは、テキストエディタおよび他のツールと組み合わせると最も強力です。
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
tools=[
{
"type": "bash_20250124",
"name": "bash"
}
],
messages=[
{"role": "user", "content": "List all Python files in the current directory."}
]
)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 outputClaudeのツール呼び出しを処理
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
}安全対策を実装
検証と制限を追加します:
def validate_command(command):
# 危険なコマンドをブロック
dangerous_patterns = ['rm -rf /', 'format', ':(){:|:&};:']
for pattern in dangerous_patterns:
if pattern in command:
return False, f"Command contains dangerous pattern: {pattern}"
# 必要に応じてさらに検証を追加
return True, NoneClaudeでテキストファイルを表示および編集