使用 fd 嵌套 while 读取循环

Nested while read loops with fd

我试图在嵌套循环中读取两个不同的输入,但没有成功。我遵循了 高级 Bash-脚本指南 的最佳答案 and also took a look at the file descriptors page

我制作的示例脚本来测试我的问题。

#!/bin/bash
while read line <&3 ; do
    echo $line
    while read _line <&4 ; do
        echo $_line
    done 4< "sample-2.txt"
done 3< "sample-1.txt"

样本内容-1.txt

Foo
Foo

样本内容-2.txt

Bar
Bar

预期输出

Foo
Bar
Bar
Foo
Bar
Bar

我得到的输出

Foo
Bar

您的文本文件没有以换行符结尾:

$ printf 'Foo\nFoo' > sample-1.txt
$ printf 'Bar\nBar' > sample-2.txt
$ bash tmp.sh
Foo
Bar
$ printf '\n' >> sample-1.txt
$ printf '\n' >> sample-2.txt
$ bash tmp.sh
Foo
Bar
Bar
Foo
Bar
Bar
如果

read 到达文件末尾而没有看到换行符,则退出状态为非零。有一个 hack 可以解决这个问题,但最好确保您的文本文件正确地以换行符结尾。

# While either read is successful or line is set anyway
while read line <&3 || [[ $line ]]; do