學習如何使用 Cursor CLI 撰寫腳本,實現自動化程式碼分析、生成與修改
-p, --print
)進行非互動式腳本和自動化操作。
--print
和 --force
在腳本中修改檔案:
# 在列印模式中啟用檔案修改
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
標誌允許 agent 直接變更檔案而無需確認# 安裝 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 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 " ✅ 讀取了 $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}s)"
echo "📊 最終統計:$tool_count 個工具,生成了 ${#accumulated_text} 個字元"
;;
esac
done
這個頁面有幫助嗎?