Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在bash中读取文件*和*stdin_Bash_Shell - Fatal编程技术网

如何在bash中读取文件*和*stdin

如何在bash中读取文件*和*stdin,bash,shell,Bash,Shell,我的任务是:逐行从文件中读取一些数据。对于每一行,如果它满足某些条件,则要求用户输入一些内容并根据用户的输入继续 我知道如何从shell脚本逐行读取内容: while read line; do echo $line done < file.txt 读行时;做 回音$线 完成

我的任务是:逐行从文件中读取一些数据。对于每一行,如果它满足某些条件,则要求用户输入一些内容并根据用户的输入继续

我知道如何从shell脚本逐行读取内容:

while read line; do
   echo $line
done < file.txt
读行时
;做
回音$线
完成
但是,如果我想在循环体中与用户交互,该怎么办。从概念上讲,我想要的是:

while read line; do
    echo "Is this what you want: $line [Y]es/[n]o"
    # Here is the problem:
    # I want to read something from standard input here.
    # However, inside the loop body, the standard input is redirected to file.txt
    read INPUT
    if [[ $INPUT == "Y" ]]; then
       echo $line
    fi
done < file.txt
读行时
;做
echo“这就是你想要的:$line[Y]es/[n]o”
#问题是:
#我想从这里的标准输入中读取一些内容。
#但是,在循环体内部,标准输入被重定向到file.txt
读取输入
如果[[$INPUT==“Y”];然后
回音$线
fi
完成

我应该用另一种方式读取文件吗?或者另一种读取标准数据的方法?

您可以在标准输入以外的文件描述符上打开文件。例如:

while read -u 3 line; do     # read from fd 3
  read -p "Y or N: " INPUT   # read from standard input
  if [[ $INPUT == "Y" ]]; then
    echo $line
  fi
done 3< file.txt             # open file on fd 3 for input
读取时-u3行;是否阅读fd 3
读取-p“Y或N:”输入#从标准输入读取
如果[[$INPUT==“Y”];然后
回音$线
fi
完成3
适合我!谢谢大家!@真是太好了!我在末尾添加了关闭fd 3,并将打开命令从输入/输出更改为仅输入。您还可以重定向循环的标准输入,而不是在读取-u 3行时使用一对
exec
s:
;做完成3
@chepner极好的想法。完成。
完成可能的重复