为什么 ksh 在嵌套命令替换期间无法捕获标准错误?

Why does ksh fail to capture standard error during nested command substitutions?

我有以下 shell 脚本。

$ cat foo.sh 
foo()
{
    A=$(uname)
    printf "hello "
    bogus
}

echo output: "$(foo 2>&1)"

它在 bash、zsh、dash 和 posh 中产生以下输出。这是有道理的,因为系统上没有名为 bogus 的命令。

$ bash foo.sh
output: hello foo.sh: line 5: bogus: command not found
$ zsh foo.sh
output: hello foo:4: command not found: bogus
$ dash foo.sh
output: hello foo.sh: 5: foo.sh: bogus: not found
$ posh foo.sh
output: hello foo.sh:8: bogus: not found

但在 Debian 上的 ksh 中,由于调用 bogus 命令,它不会打印错误消息。

$ ksh foo.sh
output: hello 

出了什么问题?

如果您想了解 shell 的系统详细信息和版本详细信息,请查看以下输出。

$ uname -a
Linux debian1 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt20-1+deb8u2 (2016-01-02) x86_64 GNU/Linux
$ cat /etc/debian_version 
8.3
$ ksh --version
  version         sh (AT&T Research) 93u+ 2012-08-01
$ dpkg -l bash zsh dash posh ksh | tail -n 5
ii  bash           4.3-11+b1      amd64        GNU Bourne Again SHell
ii  dash           0.5.7-4+b1     amd64        POSIX-compliant shell
ii  ksh            93u+20120801-1 amd64        Real, AT&T version of the Korn shell
ii  posh           0.12.3         amd64        Policy-compliant Ordinary SHell
ii  zsh            5.0.7-5        amd64        shell with lots of features

在 CentOS 系统上我看到了预期的输出。

$ cat /etc/centos-release 
CentOS release 6.7 (Final)
$ ksh --version
  version         sh (AT&T Research) 93u+ 2012-08-01
$ ksh foo.sh
output: hello foo.sh[5]: bogus: not found [No such file or directory]

如果我删除函数 foo 中的命令替换,那么所有 shell 都会在 Debian 上产生类似的输出。

$ cat bar.sh
foo()
{
    printf "hello "
    bogus
}

echo output: "$(foo 2>&1)"
$ bash bar.sh
output: hello bar.sh: line 4: bogus: command not found
$ zsh bar.sh
output: hello foo:3: command not found: bogus
$ dash bar.sh
output: hello bar.sh: 4: bar.sh: bogus: not found
$ posh bar.sh
output: hello bar.sh:7: bogus: not found
$ ksh bar.sh
output: hello bar.sh[4]: bogus: not found [No such file or directory]

为什么 ksh 在 Debian 上的第一个示例中由于 bogus 命令而没有打印错误,但在 CentOS 上却产生了错误?

我在 POSIX.1-2008 标准中找到了以下文字:

With the $(command) form, all characters following the open parenthesis to the matching closing parenthesis constitute the command. Any valid shell script can be used for command, except a script consisting solely of redirections which produces unspecified results.

我怀疑我以粗体突出显示的文本部分是造成上述示例中未指定行为的原因。但是,我不完全确定,因为我在标准中找不到 "a script consisting solely of redirections" 的定义。

我有两个问题。

  1. 我们能否充分参考标准或人来证明 页面第一个示例中 ksh 的输出是错误还是 不是吗?
  2. 我还能如何捕获 shell 编写的标准错误 shell 函数正在执行命令的函数 换人?

我搜索了这个问题并找到了以下内容:

根据标准,这是一个错误,因为每当找不到命令时都会给出 "command not found" 错误。

这是一个错误,已在 ksh 的 beta 分支中得到解决。使用那个分支。我在 ubuntu 中对其进行了测试,它对我有用。

我是这样做的:

git clone https://github.com/att/ast.git
cd ast
git checkout beta
bin/package make
cp arch/linux.i386-64/bin/ksh /usr/local/bin/ksh

master分支的ksh有很多bug。只需检查 https://github.com/att/ast/commits/beta 中的提交日志。