bash 在管道命令中从文件内容切换到 STDIN?(Linux 外壳)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1561055/
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
Switch from file contents to STDIN in piped command? (Linux Shell)
提问by zslayton
I have a program (that I did not write) which is not designed to read in commands from a file. Entering commands on STDIN is pretty tedious, so I'd like to be able to automate it by writing the commands in a file for re-use. Trouble is, if the program hits EOF, it loops infinitely trying to read in the next command dropping an endless torrent of menu options on the screen.
我有一个程序(不是我写的),它不是为了从文件中读取命令而设计的。在 STDIN 上输入命令非常乏味,因此我希望能够通过将命令写入文件中以使其自动化以供重复使用。问题是,如果程序遇到 EOF,它会无限循环,尝试在下一个命令中读取并在屏幕上放置无尽的菜单选项。
What I'd like to be able to do is cat a file containing the commands into the program via a pipe, then use some sort of shell magic to have it switch from the file to STDIN when it hits the file's EOF.
我希望能够做的是通过管道将包含命令的文件放入程序中,然后使用某种 shell 魔法让它在遇到文件的 EOF 时从文件切换到 STDIN。
Note: I've already considered using cat with the '-' for STDIN. Unfortunately (I didn't know this before), piped commands wait for the first program's output to terminate before starting the second program -- they do not run in parallel. If there's some way to get the programs to run in parallel with that kind of piping action, that would work!
注意:我已经考虑将 cat 与“-”一起用于 STDIN。不幸的是(我以前不知道这一点),管道命令在启动第二个程序之前等待第一个程序的输出终止——它们不是并行运行的。如果有某种方法可以让程序与那种管道操作并行运行,那就行了!
Any thoughts? Thanks for any assistance!
有什么想法吗?感谢您的任何帮助!
EDIT:
编辑:
I should note that my goal is not only to prevent the system from hitting the end of the commands file. I would like to be able to continue typing in commands from the keyboard when the file hits EOF.
我应该注意,我的目标不仅是防止系统到达命令文件的末尾。当文件到达 EOF 时,我希望能够继续从键盘输入命令。
回答by Idelic
I would do something like
我会做类似的事情
(cat your_file_with_commands; cat) | sh your_script
That way, when the file with commands is done, the second catwill feed your script with whatever you type on stdin afterwards.
这样,当带有命令的文件完成时,第二个cat将使用您在标准输入上输入的任何内容提供您的脚本。
回答by Guillaume
Same as Idelic answer with more simple syntax ;)
与语法更简单的 Idelic 答案相同;)
cat your_file_with_commands - | sh your_script
回答by Paused until further notice.
I would think expectwould work for this.
我认为expect会为此工作。
回答by Michiel Buddingh
Have you tried using something like tail -f commandfile | commandI think that should pipe the lines of the file to command without closing the file descriptor afterwards. Use -nto specify the number of lines to be piped if tail -fdoesn't catch all of them.
您是否尝试过使用tail -f commandfile | command我认为应该将文件的行通过管道传递给命令而不关闭文件描述符的东西。使用-n指定是否要通过管道输送的行数tail -f不赶上他们。

