bash:刷新标准输入(标准输入)
我有一个 bash 脚本,主要在交互模式下使用。然而,有时我会通过管道将一些输入输入到脚本中。在循环中处理标准输入后,我使用“-i”(交互式)复制文件。然而,这永远不会被执行(在管道模式下),因为(我猜)标准输入尚未被刷新。用一个例子来简化:
#!/bin/bash
while read line
do
echo $line
done
# the next line does not execute
cp -i afile bfile
将其放入 t.sh 中,然后执行: LS | ./t.sh
不执行读取。 我需要在读取之前刷新标准输入。它怎么能做到这一点呢?
I have a bash script that I mostly use in interactive mode. However, sometimes I pipe in some input to the script. After processing stdin in a loop, I copy a file using "-i" (interactive). However, this never gets executed (in pipe mode) since (I guess) standard input has not been flushed. To simplify with an example:
#!/bin/bash
while read line
do
echo $line
done
# the next line does not execute
cp -i afile bfile
Place this in t.sh, and execute with:
ls | ./t.sh
The read is not executed.
I need to flush stdin before the read. How could it do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这与冲洗无关。您的标准输入是 ls 的输出,您已使用 while 循环读取了所有内容,因此
read
立即获得 EOF。如果您想从终端读取内容,可以尝试以下操作:This has nothing to do with flushing. Your stdin is the output of ls, you've read all of it with your while loop, so
read
gets EOF immediately. If you want to read something from the terminal, you can try this:我不确定是否可以在这里执行您想要的操作(即让
read
从用户而不是从ls
获取输入)。问题是脚本的所有标准输入都取自管道,句点。这是相同的文件描述符,因此它不会仅仅因为您想要它而“切换”到终端。一种选择是将 ls 作为脚本的子脚本运行,如下所示:
I'm not sure it's possible to do what you want here (i.e. having the
read
take its input from the user and not fromls
). The problem is that all standard input for your script is taken from the pipe, period. This is the same file descriptor, so it will not 'switch' to the terminal just because you want it to.One option would be to run the
ls
as a child of the script, like this: