Nested while read loops with fd

混江龙づ霸主 提交于 2021-02-19 04:04:13

问题


I'm trying to read from two different inputs in nested loops without success. I've followed the best answer on this question and also took a look at the file descriptors page of the Advanced Bash-Scripting Guide.

Sample script I made to test my problem.

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

Content of sample-1.txt

Foo
Foo

Content of sample-2.txt

Bar
Bar

Expected output

Foo
Bar
Bar
Foo
Bar
Bar

The output I get

Foo
Bar

回答1:


Your text files do not end with newlines:

$ 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 has a non-zero exit status if it reaches the end of the file without seeing a newline character. There's a hack to work around that, but it's better to ensure that your text files correctly end with a newline character.

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


来源:https://stackoverflow.com/questions/42559013/nested-while-read-loops-with-fd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!