# 9.2.pkg-install、pkg-pre-install 和 pkg-post-install（安装二进制包时执行的脚本文件）

如果 Port 需要在通过 `pkg add` 或 `pkg install` 安装二进制包时执行命令，可以使用 **pkg-install**。`pkg` 会执行两次此脚本，第一次是 `${SH} pkg-install ${PKGNAME} PRE-INSTALL`，在包安装之前，第二次是 `${SH} pkg-install ${PKGNAME} POST-INSTALL`，在包安装之后。可以测试 `$2` 来确定脚本正在以哪种模式运行。`PKG_PREFIX` 环境变量设置为包的安装目录。

如果使用 **pkg-pre-install** 或 **pkg-post-install**，脚本仅运行一次（在安装包之前或之后），并且带有一个参数 `${PKGNAME}`。如果使用 **pkg-pre-install.lua** 或 **pkg-post-install.lua**，则会运行 Lua 脚本而不是 shell 脚本。通过 `pkg` 运行的 Lua 脚本提供了一些扩展功能和一些限制，这些都在 [pkg-lua-script(5)](https://man.freebsd.org/cgi/man.cgi?query=pkg-lua-script\&sektion=5\&format=html) 中进行了说明。

> **注意**
>
> 推荐使用 **pkg-pre-install**（或 **pkg-pre-install.lua**）和 **pkg-post-install**（或 **pkg-post-install.lua**），而不是使用 **pkg-install**。

这些脚本会自动添加到打包列表中。

> **重要**
>
> 这些脚本用于简化包安装后的配置。*不能* 滥用它们来启动服务、停止服务或运行任何其他会修改当前运行系统的命令。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://porters-handbook.bsdcn.org/di-9-zhang-pkg/9.2.-pkginstall-an-zhuang-er-jin-zhi-bao-shi-zhi-hang-de-jiao-ben-wen-jian.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
