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 세션에서 셸 명령을 실행할 수 있게 해주는 bash 도구에 대해 알아봅니다.

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 세션에서 셸 명령을 실행하여 시스템 작업, 스크립트 실행 및 명령줄 자동화를 수행할 수 있습니다. 셸 접근은 기본적인 에이전트 기능입니다. 셸 전용 검증을 사용하여 실제 터미널 작업을 평가하는 벤치마크인 Terminal-Bench 2.0에서 Claude는 지속적인 bash 세션에 접근할 때 강력한 성능 향상을 보여줍니다.

개요

bash 도구는 Claude에게 다음을 제공합니다:

  • 상태를 유지하는 지속적인 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 셸에서 명령을 실행합니다
  3. 출력(stdout 및 stderr)을 Claude에게 반환합니다
  4. 세션 상태는 명령 간에 유지됩니다(환경 변수, 작업 디렉토리)

매개변수

매개변수필수설명
command예*실행할 bash 명령
restart아니오bash 세션을 다시 시작하려면 true로 설정

*restart를 사용하지 않는 한 필수

예시: 다단계 자동화

Claude는 명령을 체이닝하여 복잡한 작업을 완료할 수 있습니다:

사용자 요청:
"requests 라이브러리를 설치하고 API에서 농담을 가져오는 간단한 Python 스크립트를 만든 다음 실행하세요."

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 환경 설정

    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):
        # bash에 명령 전송
        self.process.stdin.write(command + "\n")
        self.process.stdin.flush()
    
        # 타임아웃으로 출력 캡처
        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)
    
            # Claude에게 결과 반환
            tool_result = {
                "type": "tool_result",
                "tool_use_id": content.id,
                "content": result,
            }
  4. 4

    안전 조치 구현

    검증 및 제한을 추가합니다. 차단 목록은 우회하기 쉬우므로 허용 목록을 사용하세요. 체이닝된 명령이 허용 목록을 통과할 수 없도록 셸 연산자를 거부합니다:

    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"
    
        # 추가 명령을 체이닝할 수 있는 셸 연산자 거부
        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)를 전달하여 셸이 문자열을 해석하지 않도록 합니다.

오류 처리

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는 상태 비저장입니다. 애플리케이션은 턴 간에 셸 세션을 유지할 책임이 있습니다.
  • 출력 제한: 큰 출력이 자릴 수 있음
  • 스트리밍 없음: 완료 후 결과 반환

다른 도구와 결합

bash 도구는 텍스트 편집기 및 다른 도구와 결합할 때 가장 강력합니다.

코드 실행 도구도 사용 중인 경우 Claude는 두 개의 별도 실행 환경에 접근할 수 있습니다: 로컬 bash 세션과 Anthropic의 샌드박스 컨테이너입니다. 상태는 이들 간에 공유되지 않습니다. 환경을 구분하도록 Claude에 프롬프트하는 방법에 대한 지침은 다른 실행 도구와 함께 코드 실행 사용을 참조하세요.

다음 단계

도구 사용 개요

Claude와 함께 도구 사용에 대해 알아봅니다

텍스트 편집기 도구

Claude로 텍스트 파일 보기 및 편집

Was this page helpful?

  • bash 도구 구현