【问题标题】:Variable in while loop being read from unexpected source从意外源读取的 while 循环中的变量
【发布时间】:2015-03-05 06:15:11
【问题描述】:

我正在尝试将file2 的内容与file1 的内容进行比较,基于此我需要采取一些措施。

但是当我尝试从用户(变量answer)获取输入是否启动时,程序不会等待用户输入并自动获取分配给变量line的值。

#!/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

【问题讨论】:

  • 您的代码有一些拼写错误:whileread 并且缺少结束反引号。此外,您在第二个条件句中写了answer 而不是$answer

标签: bash shell unix


【解决方案1】:

您将while 循环的标准输入重定向到file2。所以在循环内部,stdin 被重定向,read 将从文件中读取,而不是从终端中读取。

使用bash,您可以使用不同的文件描述符轻松解决此问题:

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

-u3 命令行标志到read 导致它从 fd 3 读取,而 3&lt;file2 重定向将 fd 3 重定向到 file(打开 file 进行读取)。

【讨论】:

    【解决方案2】:

    @rici 提供的出色答案的另一种方法,这次不需要 bash:

    while read -r line <&3; do
      echo "$line"
      printf "Continue? " >&2
      read yesno
      case $yesno in
        [Yy]*) : ;;
        *) break ;;
      esac
    done 3<file2
    

    使用 read &lt;&amp;3 从 FD 3 读取数据,就像 bash 扩展 read -u 3 会做的那样。

    【讨论】:

      猜你喜欢
      • 2010-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-10
      • 2012-10-18
      • 2019-03-23
      • 1970-01-01
      • 2012-06-01
      相关资源
      最近更新 更多