如何在while循环读取行中从用户读取? [英] How to read from user within while-loop read line?

查看:112
本文介绍了如何在while循环读取行中从用户读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个bash文件,该文件提示用户输入一些参数,如果未提供任何内容,则使用默认值.然后,脚本继续使用参数执行其他一些命令. 这非常有效-直到最近添加都没有问题.

I had a bash file which prompted the user for some parameters and used defaults if nothing was given. The script then went on to perform some other commands with the parameters. This worked great - no problems until most recent addition.

为了尝试从txt文件读取NAMES参数,我添加了一个while循环以获取文件中的名称,但是我仍然希望提示输入其余参数.

In an attempt to read the NAMES parameter from a txt file, I've added a while-loop to take in the names in the file, but I would still like the remaining parameters prompted for.

但是,一旦我添加了while循环,输出就会在get_ans()中显示打印的提示,并且不会暂停读取,因此将选择所有默认值.

But once I added the while loop, the output shows the printed prompt in get_ans() and never pauses for a read, thus all the defaults are selected.

我想从文件中读取第一个参数,然后从提示用户读取所有后续文件.

I would like to read the first parameter from a file, then all subsequent files from prompting the user.

通过添加while循环,我有什么坏处?

What did I break by adding the while-loop?

cat list.txt | 
while read line
do 
  get_ans "Name" "$line"
  read NAME < $tmp_file

  get_ans "Name" "$line"
  read NAME < $tmp_file
done

function get_ans
{
  if [ -f $tmp_file ]; then
    rm $tmp_file

  PROMPT=$1
  DEFAULT=$2

  echo -n "$PROMPT [$DEFAULT]: "
  read ans
  if [ -z "$ans" ]; then
    ans="$DEFAULT"
  fi
  echo "$ans" > $tmp_file
}

(注意:代码不是可复制粘贴的,因此请打错字.实际代码具有在main()之前定义的功能)

(NOTE: Code is not copy&paste so please excuse typos. Actual code has function defined before the main())

推荐答案

您将数据通过管道传输到while循环STDIN中.因此,get_ans中的read也从该STDIN流中获取数据.

You pipe data into your the while loops STDIN. So the read in get_ans is also taking data from that STDIN stream.

您可以将数据通过管道传送到另一个文件描述符上的while中,以避免出现此问题并停止使用临时文件:

You can pipe data into while on a different file descriptor to avoid the issue and stop bothering with temp files:

while read -u 9 line; do
   NAME=$(get_ans Name "$line")
done 9< list.txt

get_ans() {
    local PROMPT=$1 DEFAULT=$2 ans
    read -p "$PROMPT [$DEFAULT]: " ans
    echo "${ans:-$DEFAULT}"
}

这篇关于如何在while循环读取行中从用户读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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