bash exec将输出发送到管道,如何? [英] bash exec sending output to a pipe, how?

查看:137
本文介绍了bash exec将输出发送到管道,如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试执行bash本身只是为了重定向输出.如果我使用重定向

I experiment with exec'ing the bash itself only to redirect the output. If I use redirection like

exec >bla.log
ls
exec 1>&2

它按预期方式工作:ls输出最终在bla.log中,并且在第二个exec恢复正常后,主要是因为句柄2仍绑定到终端.

it works as expected: the ls output ends up in bla.log and after the second exec things are back to normal, mainly because handle 2 is still bound to the terminal.

现在我想将输出通过管道而不是发送到文件中,这是一个简单的示例,它是exec | cat >bla.log.但是,命令立即返回.为了弄清楚发生了什么,我这样做了:

Now I thought to send the output through a pipe instead of into a file, a trivial example being exec | cat >bla.log. However, the command immediately returns. To figure out what is going on, I did this:

exec | bash -c 'echo $$; ls -l /proc/$$/fd /proc/23084/fd'

其中23084是当前正在运行的bash并获得了以下信息:

where 23084 is the bash currently running and got this:

24002
/proc/23084/fd:
total 0
lrwx------ 1 harald harald 64 Aug 14 20:17 0 -> /dev/pts/1
lrwx------ 1 harald harald 64 Aug 14 20:17 1 -> /dev/pts/1
lrwx------ 1 harald harald 64 Aug 14 20:17 2 -> /dev/pts/1
lrwx------ 1 harald harald 64 Aug 14 20:17 255 -> /dev/pts/1

/proc/24002/fd:
total 0
lr-x------ 1 harald harald 64 Aug 14 21:56 0 -> pipe:[58814]
lrwx------ 1 harald harald 64 Aug 14 21:56 1 -> /dev/pts/1
lrwx------ 1 harald harald 64 Aug 14 21:56 2 -> /dev/pts/1

我们可以看到,子流程24002确实在侦听管道.但是肯定不是打开此管道的父进程23084.

As we can see, the sub-process 24002 is indeed listening to a pipe. But it certainly is not the parent process, 23084, which has this pipe open.

有什么想法吗?

推荐答案

当命令包含管道时,每个子命令都在子shell中运行.因此,外壳程序首先为管道的每个部分派生一个子外壳程序,然后第一部分的子外壳程序执行不带任何参数的exec,该操作不执行任何操作并退出.

When a command contains a pipeline, each subcommand is run in a subshell. So the shell first forks a subshell for each part of the pipeline, and then the subshell for the first part executes exec with no arguments, which does nothing and exits.

exec被视为特殊情况.从文档中:

exec with redirection and no command is treated as a special case. From the documentation:

如果未指定命令,则任何重定向都将在 当前的shell,返回状态为0.

If command is not specified, any redirections take effect in the current shell, and the return status is 0.

这篇关于bash exec将输出发送到管道,如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆