庆典是否支持做嵌套读循环中读? [英] Does bash support doing a read nested within a read loop?

查看:125
本文介绍了庆典是否支持做嵌套读循环中读?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bash的读命令是非常方便的:

The bash read command is very convenient for:


  • 阅读 -p提示用户并从用户捕获输入

  • ,而阅读遍历文件的行进行迭代。

  • read -p to prompt the user and capture input from the user
  • while read loop to iterate through the lines of a file.

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

However, I'm having issues attempting to do both simultaneously.

例如:

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

Rather than blocking and standing by for the user to enter a choice, bash is populating $choice with the next item in the item.list file.

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

Does bash support doing a read nested within a read loop?

推荐答案

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

The simplest fix is to have the outer read read from a different file descriptor instead of standard input. In Bash, the -u option make that a little easier.

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

这篇关于庆典是否支持做嵌套读循环中读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆