问题
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