我试图在嵌套循环中读取两个不同的输入,但没有成功。我遵循了最佳答案 on this question并查看了 file descriptors page 高级 Bash 脚本指南。
我制作的示例脚本来测试我的问题。
#!/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"
sample-1.txt的内容
Foo
Foo
sample-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
关于bash - 使用 fd 嵌套 while 读取循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42559013/