gpt4 book ai didi

linux - 在 while read (stdin) 循环后暂停 bash 脚本

转载 作者:IT王子 更新时间:2023-10-29 01:21:58 34 4
gpt4 key购买 nike

我正在制作一个通过管道 (stdin) 获取输入的脚本,如 (other_command | my_script)。但是,在我阅读了整个标准输入后,我需要暂停脚本并等待用户按下回车键。

这是一个示例脚本。

#!/bin/bash

if [[ -t 0 ]]; then
echo "No stdin"
else
echo "Got stdin"
while read input; do
echo $input
done
fi

echo "Press enter to exit"
read

它是这样工作的;

$ echo text | ./script
Got stdin
text
Press enter to exit
$

它跳过了我最后的read

然而;

$ ./script
No stdin
Press enter to exit
stops here
$

从标准输入读取后如何让 read 工作?是否有同时适用于 Linux 和 OSX 的解决方案?

最佳答案

您想从用户那里读取信息。如果 stdin 不是用户,则必须从其他地方读取。典型的选择是当前终端(这里是连接到 stderr 的终端,假设有一个)。

read -p "Press enter" < "$(tty 0>&2)"

默认情况下,tty 在 stdin 上查找 tty 的名称,当 stdin 是管道时,这显然不起作用。因此,我们重定向以使其查看 stderr。

关于linux - 在 while read (stdin) 循环后暂停 bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27585415/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com