函数中的 Subshel​​l `(alias; declare -f)`

Subshell `(alias; declare -f)` in a function

我按照 man which 中的建议定义了以下 which 函数:

The recommended way to use this utility is by adding an alias (C shell) or shell function (Bourne shell) like the following:

which()
{
    (alias; declare -f) | /usr/bin/which --tty-only --read-alias --read-functions --show-tilde --show-dot $@
}
export -f which

与仅查找命令的 /usr/bin/which 不同,此函数可查找命令、别名和函数。我的问题是为什么 (alias; declare -f) 被输送到 /usr/bin/which $@?

/usr/bin/which 没有内置到 shell。因此,它无法访问 shell-内部状态(如别名或函数定义),除非将内容输入其中。

这就是这里所做的。

但是,在任何现代 shell 上 完全没有必要 。与让 shell 本身为您提供所需的输出相比,向要解析的外部程序提供 shell 语法信息本质上是不可靠的。

不要这样做。请改用 shell 内置 type