简体   繁体   English

在bash中,循环并发送命令以执行

[英]In bash, Loop and send commands to execute

Im trying to execute a program and send it commands based on a file that Im reading but as soon as I send the command the loop stop..it must be related to pipes but I would appreciate if someone could explain how they work 我试图基于我正在读取的文件执行程序并向其发送命令,但是一旦我发送命令,循环停止..它必须与管道相关,但是如果有人可以解释它们如何工作,我将不胜感激

Code: 码:

function setValue{

 echo "$1" > &9 
}

mkfifo program.fifo

./program
exec 9 > program.fifo

while read value
do 

setValue $value

done < file.csv

file.csv has 8000 rows, but the program stops after the first line...and finishes the execution without looping on any more lines of the csv file.csv有8000行,但是程序在第一行之后停止...并完成执行而不会在csv的更多行上循环

通过使管道保持打开状态以读取循环,在读取第一行之后循环不会结束,它可以继续到文件末尾:

exec 9 <> program.fifo

What is reading from program.fifo ? program.fifo读取什么? If there is no process that is reading it, then your script is blocked trying to write. 如果没有正在读取的进程,则您的脚本将被阻止尝试写入。 That write will not complete until some process is reading the fifo. 在某些进程正在读取fifo之前,该写入将不会完成。

My guess is that the code you aren't showing us in the while loop is consuming all of its stdin, which is the same as the input of the while loop. 我的猜测是,您在while循环中未显示的代码正在消耗其所有stdin,这与while循环的输入相同。 The cleanest way to avoid that is to ensure that the commands in the loop are not reading from the same file as the loop. 避免这种情况的最干净方法是确保循环中的命令不会从与循环相同的文件中读取。 There are many ways to do that; 有很多方法可以做到这一点。 I like: 我喜欢:

while read value; do {
   commands
} < /dev/null
done  < file.csv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM