【问题标题】:Bash script does not wait for user to enter responseBash 脚本不等待用户输入响应
【发布时间】:2020-11-19 08:25:37
【问题描述】:

我正在尝试读取文本文件(逐行)并在 while 循环中获取用户响应。 但是,脚本不会等待输入。相反,它只是将所有文本打印到屏幕上。

while IFS= read -r line || [ -n "$line" ]; do
    printf '%s\n' "Store $line y or n: "
    read input
    if [ $input == "y" ]
    then
        echo $line >> saved_domains.txt
    fi
done < "urls.txt"

脚本仅打印文件中的替代文本行(请参阅下图)。

Output

【问题讨论】:

  • 你永远不会要求用户在你的脚本中输入。您只需执行read input,这会导致从标准输入读取一行。您的标准输入在此处绑定到 urls.txt
  • 我假设读取命令停止执行并等待用户输入。
  • 查看 bash 手册页,其中有 SHELL BUILTIN COMMANDS 部分。它描述了readreadarray 和其他重要的 bash 命令。

标签: linux bash shell terminal


【解决方案1】:

这对我有用:

exec 3<&0
while IFS= read -r line || [ -n "$line" ]; do
    printf '%s\n' "Store $line y or n: "
    read -r -u3 input
    if [ $input == "y" ]
    then
        echo $line >> saved_domains.txt
    fi
done < "urls.txt"

【讨论】: