bash:刷新标准输入(标准输入)

发布于 2024-09-06 06:58:44 字数 342 浏览 5 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一场春暖 2024-09-13 06:58:44

这与冲洗无关。您的标准输入是 ls 的输出,您已使用 while 循环读取了所有内容,因此 read 立即获得 EOF。如果您想从终端读取内容,可以尝试以下操作:

#!/bin/bash
while read line
do
    echo $line
done
# the next line does execute 
read -p "y/n" x < /dev/tty
echo "got $x"

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:

#!/bin/bash
while read line
do
    echo $line
done
# the next line does execute 
read -p "y/n" x < /dev/tty
echo "got $x"
孤云独去闲 2024-09-13 06:58:44

我不确定是否可以在这里执行您想要的操作(即让 read 从用户而不是从 ls 获取输入)。问题是脚本的所有标准输入都取自管道,句点。这是相同的文件描述符,因此它不会仅仅因为您想要它而“切换”到终端。

一种选择是将 ls 作为脚本的子脚本运行,如下所示:

#!/bin/bash

ls | while read line
do
    echo $line
done

read -p "y/n" x
echo "got $x"

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 from ls). 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:

#!/bin/bash

ls | while read line
do
    echo $line
done

read -p "y/n" x
echo "got $x"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文