23

bash read 命令非常方便:

  • read -p 提示用户并捕获用户的输入
  • while read循环遍历文件的行。

但是,我在尝试同时进行这两种操作时遇到了问题。

例如:

#!/bin/bash

while read item
do

    echo Item: $item

    read -p "choose wisely: " choice

    echo You still have made a $choice.

done < /tmp/item.list 

bash 不是阻止并等待用户输入选择,而是使用 item.list 文件中的下一项填充 $choice。

bash 是否支持嵌套在读取循环中的读取?

4

1 回答 1

36

最简单的解决方法是read从不同的文件描述符而不是标准输入进行外部读取。在 Bash 中,该-u选项使这更容易一些。

while read -u 3 item
do
  # other stuff
  read -p "choose wisely: " choice
  # other stuff
done 3< /tmp/item.list
于 2013-04-30T20:09:22.180 回答