【问题标题】:Pause bash script after while read (stdin) loop在读取(stdin)循环后暂停 bash 脚本
【发布时间】:2014-12-20 23:42:24
【问题描述】:

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

这是一个示例脚本。

#!/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 的解决方案?

【问题讨论】:

    标签: linux bash stdin


    【解决方案1】:

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

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

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

    【讨论】:

    • 好点,但是,tty sais not a tty 如果像这样运行。 /dev/ttys006 否则。因此,read &lt; "/dev/ttys006" 有效,但不可行。
    • 你确定你没有错过任何地方的命令吗? "$(tty)" 只是说 **execute tty 并提供引用的结果。 tty 会返回类似/dev/ttys006 的东西(取决于系统/终端)。所以"$(tty)" 应该完全做到"/dev/ttys006" 在你的终端中执行以下命令来检查( mytty="$(tty)"; echo "tty: $mytty" )
    • echo "tty" &gt; test; sh test; echo string | sh test 显示一行带有/dev/ttys006,另一行带有not a tty。发生在我的 OSX 和 Linux 测试中。
    • 在编辑时添加 0>&2 后就像魅力一样。 :)
    • 您介意快速总结一下为什么 0>&2 有效吗?这将使答案更完整。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    相关资源
    最近更新 更多