Linux Bash:从文件中读取标准输入并将标准输出写入文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15680530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash: read stdin from file and write stdout to file
提问by alexandernst
I'm trying to run an app (let's say top
) so it will read from a file for stdin and write to another file from stdout.
我正在尝试运行一个应用程序(假设top
),因此它将从 stdin 的文件中读取并从 stdout 写入另一个文件。
Currently I have
目前我有
mkfifo stdin.pipe
(tail -f stdin.pipe) | top
which works as expected, as I can then echo
something to that file and top will receive it.
But I'm unable to redirect the output of top.
How can I achieve this?
它按预期工作,因为我可以echo
对该文件进行一些操作,top 将收到它。但我无法重定向 top 的输出。我怎样才能做到这一点?
EDIT:
编辑:
Ok, let's scratch top. I'm testing with this:
好的,让我们从头开始。我正在测试这个:
cat test.sh
echo Say something
read something
echo you said $something
采纳答案by cdarke
Let's forget about top
, that appears to be a red herring.
让我们忘记top
,这似乎是一个红鲱鱼。
To map stdin or stdout to files, you can use redirection:
要将 stdin 或 stdout 映射到文件,您可以使用重定向:
some_program < input_file # Redirects stdin
another_program > output_file # Redirects stdout
or even:
甚至:
yet_another < input_file > output_file
回答by Joni
Is there a way I can map stdin and stdout to files and use them to control a cli app?
有没有办法可以将 stdin 和 stdout 映射到文件并使用它们来控制 cli 应用程序?
It sounds like you are looking for coprocesses, added to Bash in 4.0.
听起来您正在寻找在 4.0 中添加到 Bash 的coprocesses。
coproc cat # Start cat in background
echo Hello >&${COPROC[1]} # Say "Hello" to cat
read LINE <&${COPROC[0]} # Read response
echo $LINE # cat replied "Hello"!
Before 4.0 you had to use two named pipes to achieve this.
在 4.0 之前,您必须使用两个命名管道来实现这一点。