bash 도구를 사용하면 Claude가 지속적인 bash 세션에서 셸 명령을 실행할 수 있으므로 시스템 작업, 스크립트 실행 및 명령줄 자동화가 가능합니다.
bash 도구는 Claude에게 다음을 제공합니다:
| 모델 | 도구 버전 |
|---|---|
| Claude 4 모델 및 Sonnet 3.7 (지원 중단됨) | bash_20250124 |
이전 도구 버전은 최신 모델과의 하위 호환성이 보장되지 않습니다. 항상 모델 버전에 해당하는 도구 버전을 사용하세요.
bash 도구는 지속적인 세션을 유지합니다:
| 매개변수 | 필수 | 설명 |
|---|---|---|
command | 예* | 실행할 bash 명령 |
restart | 아니오 | bash 세션을 다시 시작하려면 true로 설정 |
*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로 텍스트 파일 보기 및 편집