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

ddo*_*xey 22 bash

bash read命令非常方便:

  • 读取 -p以提示用户并捕获用户的输入
  • 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 
Run Code Online (Sandbox Code Playgroud)

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

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

小智 32

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

while read -u 3 item
do
  # other stuff
  read -p "choose wisely: " choice
  # other stuff
done 3< /tmp/item.list
Run Code Online (Sandbox Code Playgroud)

  • 只需将`read -p“明智地选择:”选择`更改为`read -p“明智地选择:”选择&lt;/dev/tty`也应该有效。 (4认同)