스크립트와 자동화 워크플로에서 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
# Simple codebase question

cursor-agent -p --output-format text "What does this codebase do?"

자동 코드 리뷰

구조화된 분석이 필요하면 --output-format json을 써:
#!/bin/bash
# simple-code-review.sh - Basic code review script

echo "Starting code review..."

# Review recent changes
cursor-agent -p --force --output-format text \
  "Review the recent code changes and provide feedback on:
  - Code quality and readability  
  - Potential bugs or issues
  - Security considerations
  - Best practices compliance

  Provide specific suggestions for improvement and write to review.txt"

if [ $? -eq 0 ]; then
  echo "✅ Code review completed successfully"
else
  echo "❌ Code review failed"
  exit 1
fi

실시간 진행 상황 추적

실시간 진행 상황을 추적하려면 --output-format stream-json을 써:
#!/bin/bash
# stream-progress.sh - Track progress in real-time

echo "🚀 Starting stream processing..."

# Track progress in real-time
accumulated_text=""
tool_count=0
start_time=$(date +%s)

cursor-agent -p --force --output-format stream-json \
  "Analyze this project structure and create a summary report in 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 "🤖 Using model: $model"
        fi
        ;;
        
      "assistant")
        # Accumulate streaming text deltas
        content=$(echo "$line" | jq -r '.message.content[0].text // empty')
        accumulated_text="$accumulated_text$content"
        
        # Show live progress
        printf "\r📝 Generating: %d chars" ${#accumulated_text}
        ;;
        
      "tool_call")
        if [ "$subtype" = "started" ]; then
          tool_count=$((tool_count + 1))
          
          # Extract tool information
          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 #$tool_count: Creating $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 #$tool_count: Reading $path"
          fi
          
        elif [ "$subtype" = "completed" ]; then
          # Extract and show tool results
          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 "   ✅ Created $lines lines ($size bytes)"
          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 "   ✅ Read $lines 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🎯 Completed in ${duration}ms (${total_time}s total)"
        echo "📊 Final stats: $tool_count tools, ${#accumulated_text} chars generated"
        ;;
    esac
  done