学习如何使用 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 \
"审查最近的代码更改并提供以下方面的反馈:
- 代码质量和可读性
- 潜在的 bug 或问题
- 安全考虑
- 最佳实践合规性
提供具体的改进建议并写入 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}s)"
echo "📊 最终统计:$tool_count 个工具,生成了 ${#accumulated_text} 个字符"
;;
esac
done
此页面对您有帮助吗?