钩庆典中的所有命令的输出 [英] Hook all command output within bash

查看:153
本文介绍了钩庆典中的所有命令的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是为了好玩我要管的终端 espeak的所有输出文本。例如,该设置后,我应该能够键入回声喜键,听到喜细语,或 LS 听我的目录内容列出。

Just for fun I want to pipe all output text in a terminal to espeak. For example, after this is set up I should be able to type echo hi and hear "hi" spoken, or ls and hear my directory contents listed.

捕捉到输出的唯一前途的方法,我发现到目前为止,从这里:的 http://www.linuxjournal.com/content/bash-redirections-using-exec

The only promising method to capture output I've found so far is from here: http://www.linuxjournal.com/content/bash-redirections-using-exec

这是我迄今为止:

npipe=/tmp/$$.tmp
mknod $npipe p
tee /dev/tty <$npipe | espeak &
espeakpid=$!
exec 1>&-
exec 1>$npipe
trap "rm -f $npipe; kill $espeakpid" EXIT

它的工作原理(也印了一堆完成的作业),但创建命名管道,与陷阱删除和打印输出 T恤一切只是似乎有点乱。有没有更简单的方法吗?

It works (also printing a bunch of "Done" jobs), but creating the named pipe, removing with trap and printing the output with tee all just seems a bit messy. Is there a simpler way?

推荐答案

这是一个方法:

exec > >(exec tee >(exec xargs -n 1 -d '\n' espeak -- &>/dev/null))

如果您希望能够恢复到原来的输出流:

If you want to be able to restore back to original output stream:

exec 3>&1  ## Store original stdout to fd 3.
exec 4> >(exec tee >(exec xargs -n 1 -d '\n' espeak -- &>/dev/null))  ## Open "espeak" as fd 4.
exec >&4  ## Redirect stdout to "espeak".
exec >&3  ## Redirect back to normal.


  • 我用 xargs的-n 1 ,因为 espeak的没有做任何事情,直到EOF到达,所以我们召唤它的实例,每行。这种可定制的课程,但有你的答案。当然还有而读循环也可以是这样的一个选项。

  • 我也用 EXEC 的过程中替换,以确保我们摆脱不必要的子shell的。

    • I use xargs -n 1 because espeak doesn't do anything until EOF is reached so we summon an instance of it per line. This can be customized of course, but there's your answer. And of course a while read loop can also be an option for this.
    • I also use exec's in process substitution to make sure we get rid of unnecessary subshells.
    • 这篇关于钩庆典中的所有命令的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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