{"meta":{"title":"快速入门：利用GitHub Copilot CLI实现自动化","intro":"使用 Copilot CLI 在几分钟内创建自动化程序。","product":"GitHub Copilot","breadcrumbs":[{"href":"/zh/copilot","title":"GitHub Copilot"},{"href":"/zh/copilot/how-tos","title":"操作方法"},{"href":"/zh/copilot/how-tos/copilot-cli","title":"Copilot CLI"},{"href":"/zh/copilot/how-tos/copilot-cli/automate-copilot-cli","title":"使用 Copilot CLI 自动化"},{"href":"/zh/copilot/how-tos/copilot-cli/automate-copilot-cli/quickstart","title":"快速入门"}],"documentType":"article"},"body":"# 快速入门：利用GitHub Copilot CLI实现自动化\n\n使用 Copilot CLI 在几分钟内创建自动化程序。\n\n## 概述\n\n可以使用 GitHub Copilot CLI 以编程方式运行Copilot提示。 有两种主要方法可以执行此操作：\n\n* 直接从终端运行Copilot CLI提示。\n* 编写利用 Copilot CLI的脚本或自动化。\n\n本指南将引导你完成每个选项的简单用例。\n\n## 从命令行运行提示\n\n如果要在不启动交互式会话的情况下传递 Copilot CLI 提示，请使用 `-p` 标志。\n\n```shell copy\ncopilot -p \"Summarize what this file does: ./README.md\"\n```\n\n在交互式会话中键入的任何命令都与 `-p` 兼容。\n\n## 在脚本中使用Copilot CLI\n\n编程模式的真正功能来自编写脚本以自动执行 AI 驱动的任务。 在脚本中，可以生成提示，或将提示部分替换为动态内容，然后捕获输出或将其传递给脚本的其他部分。\n\n让我们创建一个脚本，该脚本查找当前目录中大于 10 MB 的所有文件，用于 Copilot CLI 生成每个文件的简要说明，然后通过电子邮件发送摘要报告。\n\n1. 在存储库中，创建一 `find_large_files.sh` 个名为的新文件并添加以下内容。\n\n   ```bash copy\n   #!/bin/bash\n   # Find files over 10 MB, use Copilot CLI to describe them, and email a summary\n\n   EMAIL_TO=\"user@example.com\"\n   SUBJECT=\"Large file found\"\n   BODY=\"\"\n\n   while IFS= read -r -d '' file; do\n       size=$(du -h \"$file\" | cut -f1)\n       description=$(copilot -p \"Describe this file briefly: $file\" -s 2>/dev/null)\n       BODY+=\"File: $file\"$'\\n'\"Size: $size\"$'\\n'\"Description:     $description\"$'\\n\\n'\n   done < <(find . -type f -size +10M -print0)\n\n   if [ -z \"$BODY\" ]; then\n       echo \"No files over 10MB found.\"\n       exit 0\n   fi\n\n   echo -e \"To: $EMAIL_TO\\nSubject: $SUBJECT\\n\\n$BODY\" | sendmail \"$EMAIL_TO\"\n   echo \"Email sent to $EMAIL_TO with large file details.\"\n   ```\n\n2. 使脚本可执行。\n\n   ```shell copy\n   chmod +x find_large_files.sh\n   ```\n\n3. 运行脚本。\n\n   ```shell copy\n   ./find_large_files.sh\n   ```\n\n此脚本利用 Copilot CLI 来生成您正在搜索的文件的描述，以便快速了解大型文件的内容，而无需打开它们。\n\n你还可以响应事件自动触发这些脚本，例如向目录添加新文件，或通过使用 cron 作业和 CI/CD 管道在计划时间触发脚本。\n\n## 延伸阅读\n\n* [以编程方式运行GitHub Copilot CLI](/zh/copilot/how-tos/copilot-cli/automate-copilot-cli/run-cli-programmatically)\n* [使用 Copilot CLI 和 GitHub Actions 自动执行任务](/zh/copilot/how-tos/copilot-cli/automate-copilot-cli/automate-with-actions)\n* [GitHub Copilot 命令行界面编程参考](/zh/copilot/reference/copilot-cli-reference/cli-programmatic-reference)"}