# 快速入门：利用GitHub Copilot CLI实现自动化

使用 Copilot CLI 在几分钟内创建自动化程序。

## 概述

可以使用 GitHub Copilot CLI 以编程方式运行Copilot提示。 有两种主要方法可以执行此操作：

* 直接从终端运行Copilot CLI提示。
* 编写利用 Copilot CLI的脚本或自动化。

本指南将引导你完成每个选项的简单用例。

## 从命令行运行提示

如果要在不启动交互式会话的情况下传递 Copilot CLI 提示，请使用 `-p` 标志。

```shell copy
copilot -p "Summarize what this file does: ./README.md"
```

在交互式会话中键入的任何命令都与 `-p` 兼容。

## 在脚本中使用Copilot CLI

编程模式的真正功能来自编写脚本以自动执行 AI 驱动的任务。 在脚本中，可以生成提示，或将提示部分替换为动态内容，然后捕获输出或将其传递给脚本的其他部分。

让我们创建一个脚本，该脚本查找当前目录中大于 10 MB 的所有文件，用于 Copilot CLI 生成每个文件的简要说明，然后通过电子邮件发送摘要报告。

1. 在存储库中，创建一 `find_large_files.sh` 个名为的新文件并添加以下内容。

   ```bash copy
   #!/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."
   ```

2. 使脚本可执行。

   ```shell copy
   chmod +x find_large_files.sh
   ```

3. 运行脚本。

   ```shell copy
   ./find_large_files.sh
   ```

此脚本利用 Copilot CLI 来生成您正在搜索的文件的描述，以便快速了解大型文件的内容，而无需打开它们。

你还可以响应事件自动触发这些脚本，例如向目录添加新文件，或通过使用 cron 作业和 CI/CD 管道在计划时间触发脚本。

## 延伸阅读

* [以编程方式运行GitHub Copilot CLI](/zh/copilot/how-tos/copilot-cli/automate-copilot-cli/run-cli-programmatically)
* [使用 Copilot CLI 和 GitHub Actions 自动执行任务](/zh/copilot/how-tos/copilot-cli/automate-copilot-cli/automate-with-actions)
* [GitHub Copilot 命令行界面编程参考](/zh/copilot/reference/copilot-cli-reference/cli-programmatic-reference)