在读取(stdin)循环后暂停bash脚本

xeo*_*eor 4 linux bash stdin

我正在制作一个脚本,该脚本通过管道(stdin)进行输入,如(other_command | my_script)中所示。但是,在阅读完整个stdin之后,我需要暂停脚本并等待用户按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
Run Code Online (Sandbox Code Playgroud)

它像这样工作;

$ echo text | ./script
Got stdin
text
Press enter to exit
$
Run Code Online (Sandbox Code Playgroud)

它跳过了我的决赛read

然而;

$ ./script
No stdin
Press enter to exit
stops here
$
Run Code Online (Sandbox Code Playgroud)

read从stdin阅读后,如何上班?有没有可以在Linux和OSX上都可以使用的解决方案?

tha*_*guy 5

您要向用户阅读。如果不是stdin用户,则必须从其他地方阅读。典型的选择是电流端子(此处是连接到stderr的端子,假设有一个端子)。

read -p "Press enter" < "$(tty 0>&2)"
Run Code Online (Sandbox Code Playgroud)

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