코드 분석, 생성, 리팩토링 작업을 위한 스크립트와 자동화 워크플로우에서 Cursor CLI를 활용해보자.

작동 방식

비대화형 스크립팅 및 자동화를 위해 print 모드 (-p, --print)를 사용해.

스크립트에서 파일 수정

스크립트에서 파일을 수정하려면 --print--force를 함께 사용해:
# print 모드에서 파일 수정 활성화
cursor-agent -p --force "이 코드를 최신 ES6+ 문법을 사용하도록 리팩터링해"

# --force 없이는 변경사항이 제안만 되고 적용되지 않음
cursor-agent -p "이 파일에 JSDoc 주석 추가해"  # 파일을 수정하지 않음

# 실제 파일 변경을 포함한 배치 처리
find src/ -name "*.js" | while read file; do
  cursor-agent -p --force "$file에 포괄적인 JSDoc 주석 추가해"
done
--force 플래그는 에이전트가 확인 없이 직접 파일을 변경할 수 있게 해줘

설정

전체 설정 방법은 설치인증을 참고해.
# Cursor CLI 설치
curl https://cursor.com/install -fsS | bash

# 스크립트용 API 키 설정  
export CURSOR_API_KEY=your_api_key_here
cursor-agent -p "Analyze this code"

예제 스크립트

다양한 스크립트 요구사항에 맞게 서로 다른 출력 형식을 사용해. 자세한 내용은 출력 형식을 참고해.

코드베이스 검색

읽기 쉬운 응답을 위해 --output-format text를 사용해:
#!/bin/bash
# 간단한 코드베이스 질문

cursor-agent -p --output-format text "이 코드베이스는 무엇을 하나요?"

자동화된 코드 리뷰

구조화된 분석을 위해 --output-format json을 사용해:
#!/bin/bash
# simple-code-review.sh - 기본 코드 리뷰 스크립트

echo "코드 리뷰를 시작합니다..."

# 최근 변경사항 리뷰
cursor-agent -p --force --output-format text \
  "최근 코드 변경사항을 리뷰하고 다음 항목에 대한 피드백을 제공해:
  - 코드 품질과 가독성  
  - 잠재적 버그나 문제점
  - 보안 고려사항
  - 모범 사례 준수

  개선을 위한 구체적인 제안을 제공하고 review.txt에 작성해"

if [ $? -eq 0 ]; then
  echo "✅ 코드 리뷰가 성공적으로 완료되었습니다"
else
  echo "❌ 코드 리뷰가 실패했습니다"
  exit 1
fi

실시간 진행 상황 추적

실시간 진행 상황 추적을 위해 --output-format stream-json을 사용해:
#!/bin/bash
# stream-progress.sh - 실시간으로 진행 상황 추적

echo "🚀 스트림 처리를 시작합니다..."

# 실시간으로 진행 상황 추적
accumulated_text=""
tool_count=0
start_time=$(date +%s)

cursor-agent -p --force --output-format stream-json \
  "이 프로젝트 구조를 분석하고 analysis.txt에 요약 보고서를 작성해" | \
  while IFS= read -r line; do
    
    type=$(echo "$line" | jq -r '.type // empty')
    subtype=$(echo "$line" | jq -r '.subtype // empty')
    
    case "$type" in
      "system")
        if [ "$subtype" = "init" ]; then
          model=$(echo "$line" | jq -r '.model // "unknown"')
          echo "🤖 사용 중인 모델: $model"
        fi
        ;;
        
      "assistant")
        # 스트리밍 텍스트 델타 누적
        content=$(echo "$line" | jq -r '.message.content[0].text // empty')
        accumulated_text="$accumulated_text$content"
        
        # 실시간 진행 상황 표시
        printf "\r📝 생성 중: %d자" ${#accumulated_text}
        ;;
        
      "tool_call")
        if [ "$subtype" = "started" ]; then
          tool_count=$((tool_count + 1))
          
          # 도구 정보 추출
          if echo "$line" | jq -e '.tool_call.writeToolCall' > /dev/null 2>&1; then
            path=$(echo "$line" | jq -r '.tool_call.writeToolCall.args.path // "unknown"')
            echo -e "\n🔧 도구 #$tool_count: $path 생성 중"
          elif echo "$line" | jq -e '.tool_call.readToolCall' > /dev/null 2>&1; then
            path=$(echo "$line" | jq -r '.tool_call.readToolCall.args.path // "unknown"')
            echo -e "\n📖 도구 #$tool_count: $path 읽는 중"
          fi
          
        elif [ "$subtype" = "completed" ]; then
          # 도구 결과 추출 및 표시
          if echo "$line" | jq -e '.tool_call.writeToolCall.result.success' > /dev/null 2>&1; then
            lines=$(echo "$line" | jq -r '.tool_call.writeToolCall.result.success.linesCreated // 0')
            size=$(echo "$line" | jq -r '.tool_call.writeToolCall.result.success.fileSize // 0')
            echo "   ✅ $lines줄 생성됨 ($size바이트)"
          elif echo "$line" | jq -e '.tool_call.readToolCall.result.success' > /dev/null 2>&1; then
            lines=$(echo "$line" | jq -r '.tool_call.readToolCall.result.success.totalLines // 0')
            echo "   ✅ $lines줄 읽음"
          fi
        fi
        ;;
        
      "result")
        duration=$(echo "$line" | jq -r '.duration_ms // 0')
        end_time=$(date +%s)
        total_time=$((end_time - start_time))
        
        echo -e "\n\n🎯 ${duration}ms에 완료 (총 ${total_time}초)"
        echo "📊 최종 통계: 도구 $tool_count개, ${#accumulated_text}자 생성됨"
        ;;
    esac
  done