在while循环变量从意想不到源读取 [英] Variable in while loop being read from unexpected source

查看:155
本文介绍了在while循环变量从意想不到源读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图文件2 的内容与文件1 的比较和基于我需要一些行动。

但是,当我尝试采取从用户输入(变量答案)是否启动与否,程序不等待用户输入和需要赋给变量的值自动。

 #!/斌/庆典而读线;

VAR =`grep的$行file1.txt`如果[-z$ VAR]
然后
    回声$线未运行
    回声你想启动?(Y / N)
    阅读答案
    如果[$回答=Y] || [$回答='N']
    然后
        如果[$回答=Y]
        然后
        (一些行动)
        其他
        (行动)
        科幻
    其他
    (行动)
    科幻
科幻完成<文件2


解决方案

您重定向为,而循环文件2 。因此,在循环中,标准输入被重定向和会从文件中读取,而不是从终端。

使用庆典,你可以很容易地解决这个问题,通过使用不同的文件描述符:

 同时读取-r -u3线;做
  回声$线
  阅读-p是否继续?YESNO
  如果[[$ YESNO = [YY] *]!]再突破;科幻
做3'; file2的

-u3 命令行标志,以使其从FD 3读取,而 3';文件2 重定向重定向FD 3 文件(开放文件的在读)。

I am trying to compare the content of file2 with that of file1 and based on that I need to take some action.

But when I try to take input from user (in variable answer) whether to start or not, the program does not wait for user input and takes value assigned to variable line automatically.

#!/bin/bash

while read line;
do 
var=`grep $line file1.txt`

if [ -z "$var"] 
then 
    echo "$line is not running"
    echo "Do you want to start? (Y/N)"
    read answer
    if [ "$answer" = 'Y' ] || [ "$answer" = 'N' ]
    then
        if [ "$answer" = 'Y' ]
        then
        (some action)
        else
        (action)
        fi
    else
    (action)
    fi
fi

done < file2

解决方案

You redirect stdin for the while loop to file2. So inside the loop, stdin is redirected and a read will read from the file, not from the terminal.

With bash, you can easily fix that by using a different file descriptor:

while read -r -u3 line; do
  echo "$line"
  read -p "Continue? " yesno
  if [[ $yesno != [Yy]* ]]; then break; fi
done 3<file2

The -u3 command-line flag to read causes it to read from fd 3, while the 3<file2 redirection redirects fd 3 to file (opening file for reading).

这篇关于在while循环变量从意想不到源读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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