使用 Cursor 命令行界面在腳本和自動化工作流中執行代碼分析、生成和重構任務。
工作方式¶
使用 print 模式 (-p, --print) 進行非交互式腳本編寫和自動化。
在腳本中修改文件¶
在腳本中,將 --print 與 --force (或 --yolo) 結合使用即可修改文件:
# 在 print 模式下允許修改文件
agent -p --force "Refactor this code to use modern ES6+ syntax"
# 不使用 --force 時,只會建議更改,不會實際應用
agent -p "Add JSDoc comments to this file" # 不會修改文件
# 批量處理並實際修改文件
find src/ -name "*.js" | while read file; do
agent -p --force "Add comprehensive JSDoc comments to $file"
done
--force 標誌允許智能體無需確認,直接修改文件
設置¶
# 安裝 Cursor 命令行界面(macOS、Linux、WSL)
curl https://cursor.com/install -fsS | bash
# 安裝 Cursor 命令行界面(Windows PowerShell)
irm 'https://cursor.com/install?win32=true' | iex
# 爲腳本設置 API 密鑰
export CURSOR_API_KEY=your_api_key_here
agent -p "Analyze this code"
示例腳本¶
根據不同的腳本需求使用不同的輸出格式。詳見輸出格式。
搜索代碼庫¶
默認情況下,--print 使用 text 格式,僅輸出簡潔的最終答案:
#!/bin/bash
# 簡單的代碼庫問題 - 默認使用文本格式
agent -p "What does this codebase do?"
自動代碼評審¶
使用 --output-format json 獲取結構化分析結果:
#!/bin/bash
# simple-code-review.sh - 基礎代碼評審腳本
echo "Starting code review..."
# 評審近期更改
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 按消息級別跟蹤進度,或添加 --stream-partial-output 以流式獲取增量輸出:
#!/bin/bash
# stream-progress.sh - 即時跟蹤進度
echo "🚀 Starting stream processing..."
# 即時跟蹤進度
accumulated_text=""
tool_count=0
start_time=$(date +%s)
agent -p --force --output-format stream-json --stream-partial-output \
"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")
# 僅處理流式增量(包含 timestamp_ms,且不包含 model_call_id)。
# 跳過工具調用前和輪次結束時的緩衝內容刷新。
has_ts=$(echo "$line" | jq 'has("timestamp_ms")')
has_mc=$(echo "$line" | jq 'has("model_call_id")')
if [ "$has_ts" = "true" ] && [ "$has_mc" = "false" ]; then
content=$(echo "$line" | jq -r '.message.content[0].text // empty')
accumulated_text="$accumulated_text$content"
printf "\r📝 Generating: %d chars" ${#accumulated_text}
fi
;;
"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 #$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
# 提取並顯示工具結果
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
使用圖像¶
要向智能體發送圖像、媒體文件或其他二進制數據,請在提示詞中提供文件路徑。智能體可通過工具調用讀取任何文件,包括圖像、視頻和其他格式的文件。
在提示詞中加入文件路徑¶
只需在提示詞中引用文件路徑。智能體會在需要時自動讀取相應文件:
# 分析圖像
agent -p "Analyze this image and describe what you see: ./screenshot.png"
# 處理多個媒體文件
agent -p "Compare these two images and identify differences: ./before.png ./after.png"
# 在文本指令中結合使用文件路徑
agent -p "Review the code in src/app.ts and the design mockup in designs/homepage.png. Suggest improvements to match the design."
工作原理¶
當您在提示詞中包含文件路徑時:
- 智能體會收到包含文件路徑引用的提示詞
- 智能體會通過工具調用自動讀取文件
- 圖像會被自動處理
- 您可以使用相對路徑或絕對路徑引用文件
示例:圖像分析腳本¶
#!/bin/bash
# analyze-image.sh - 使用 Headless CLI 分析圖像
IMAGE_PATH="./screenshots/ui-mockup.png"
agent -p --output-format json \
"Analyze this image and provide a detailed description: $IMAGE_PATH" | \
jq -r '.result'
示例:批量處理媒體文件¶
#!/bin/bash
# process-media.sh - 批量處理媒體文件
for image in images/*.png; do
echo "Processing $image..."
agent -p --output-format text \
"Describe what's in this image: $image" > "${image%.png}.description.txt"
done
文件路徑可以是相對於當前工作目錄的相對路徑,也可以是絕對路徑。
智能體會通過工具調用讀取文件,因此請確保文件存在,
並可從運行命令的位置訪問。