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