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

查看:13
本文介绍了如何在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.

您可以将数据通过管道传输到不同的文件描述符上,以避免出现此问题并不再为临时文件烦恼:

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天全站免登陆