2013-04-30 62 views
15

bash的读命令是用于很方便:庆典是否支持做嵌套在读取循环中读?

  • -p,以提示用户,并从用户
  • 捕获输入而环通过一个文件的行进行迭代。

不过,我在试图同时做这两个问题。

例如:

#!/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文件的下一个项目。

庆典是否支持做嵌套在读取循环中读?

+1

要记住的两件事是1)内循环从外循环中继承其文件描述符,2)可以使用其他文件描述符而不是标准输入。的 – chepner 2013-04-30 20:44:54

+0

可能重复[bash的:这也是使用读出的环路内嵌套交互式读取](http://stackoverflow.com/questions/11704353/bash-nested-interactive-read-within-a-loop-thats-also-using -读) – Sparhawk 2014-07-30 07:03:53

回答

25

最简单的解决方法是让外部read从不同的文件 中读取而不是标准输入。在bash中-u选项使之成为 更容易一些。

while read -u 3 item 
do 
    # other stuff 
    read -p "choose wisely: " choice 
    # other stuff 
done 3< /tmp/item.list