相关疑难解决方法(0)

在while循环中读取bash中的输入

我有一个bash脚本,如下所示,

cat filename | while read line
do
    read input;
    echo $input;
done
Run Code Online (Sandbox Code Playgroud)

但这显然没有给我正确的输出,因为当我在while循环中读取它时,它试图从文件文件名读取,因为可能的I/O重定向.

还有其他方法吗?

bash while-loop

93
推荐指数
2
解决办法
10万
查看次数

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

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

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

while read line; do
   echo $line
done < file.txt
Run Code Online (Sandbox Code Playgroud)

但是,如果我想做什么与用户交互的内部循环体.从概念上讲,这就是我想要的:

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
Run Code Online (Sandbox Code Playgroud)

我应该用另一种方式来读取文件吗?或者另一种读stdin的方法?

bash shell

3
推荐指数
1
解决办法
1085
查看次数

标签 统计

bash ×2

shell ×1

while-loop ×1