在函数中调用作业时无法 grep 作业列表

bis*_*hop 7 bash pipe function jobs subshell

我可以grep输出jobs,我可以grep输出 a function。但是为什么我不能jobs在函数中grep 输出呢?

$ # yes, i can grep jobs
$ jobs
[1]+  Running          vim
[2]+  Stopped          matlab

$ jobs | grep vim
[1]+  Running          vim

$ # yes, of course i can grep a function
$ type mockjobs
mockjobs is a function
mockjobs ()
{
    echo '[1]+ Running         vim banjo'
}
$ mockjobs | grep vim
[1]+ Running         vim banjo

$ # now put those two together and surely I can grep???
$ type realjobs
realjobs is a function
realjobs ()
{
    jobs
}
$ realjobs | grep vim
$ # Nope, WTF?

$ bash --version
GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)

$ # funny though, redirection works just fine:
$ tmpfile=$(mktemp); realjobs > $tmpfile; grep vim $tmpfile; rm $tmpfile
[1]+  Running          vim
Run Code Online (Sandbox Code Playgroud)

我在 bash 列表中没有看到错误,但也许我错过了?在 Bash 2.02 中提到了一个问题,当它jobs是管道的一部分时,但在我能找到的功能中没有最新的。

我在这里缺少什么?

bis*_*hop 8

Eric Blake在 bash-bugs 邮件列表上回答

jobs是一个有趣的内置函数 - 父 shell 中的作业集与子 shell 中的作业集不同。Bash 通常会创建一个子外壳来执行管道,并且由于该子外壳中没有作业,因此作业的隐藏执行无需报告。

Bash 具有特殊情况的代码,jobs |当它可以明显地告诉您正在运行内置作业作为管道左侧的唯一命令时,而是报告父 shell 的作业,但该特殊情况代码不能踢如果您隐藏作业的执行,无论是像您一样将其隐藏在函数中,还是通过其他方式,例如: eval jobs | grep vim