運作方式
-p, --print
)。
在腳本中修改檔案
--print
搭配 --force
一起使用,以在腳本中修改檔案:
Copy
Ask AI
# 在列印模式下允許修改檔案
cursor-agent -p --force "Refactor this code to use modern ES6+ syntax"
# 若未加上 --force,變更只會被建議,不會套用
# 不會修改檔案
# 批次處理並實際變更檔案
find src/ -name "*.js" | while read file; do
cursor-agent -p --force "為 $file 新增完整的 JSDoc 註解"
done
--force
旗標允許 agent 在無需確認的情況下直接修改檔案設定
Copy
Ask AI
# 安裝 Cursor CLI
curl https://cursor.com/install -fsS | bash
# 為腳本設定 API 金鑰
export CURSOR_API_KEY=your_api_key_here
cursor-agent -p "分析這段程式碼"
範例腳本
搜尋程式碼庫
--output-format text
取得易讀的回應:
Copy
Ask AI
#!/bin/bash
# 簡單的程式庫問題
cursor-agent -p --output-format text "這個程式庫是做什麼的?"
自動化程式碼審查
--output-format json
取得結構化分析:
Copy
Ask AI
#!/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
來即時追蹤進度:
Copy
Ask AI
#!/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 "🤖 Using model: $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}s)"
echo "📊 最終統計:$tool_count 個工具,已產生 ${#accumulated_text} 個字元"
;;
esac
done