【问题标题】:Nested while read loops with fd使用 fd 嵌套 while 读取循环
【发布时间】:2017-03-02 15:09:34
【问题描述】:

我试图在嵌套循环中读取两个不同的输入,但没有成功。我关注了最佳答案 on this question 并查看了 Advanced Bash-Scripting Guidefile 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"

sample-1.txt 的内容

Foo
Foo

sample-2.txt 的内容

Bar
Bar

预期输出

Foo
Bar
Bar
Foo
Bar
Bar

我得到的输出

Foo
Bar

【问题讨论】:

  • 我在bash 3.2.57 和 4.4.12 中都得到了预期的输出。我怀疑您的文本文件在最后一行的末尾没有换行符。
  • @Lapsusone, ...顺便说一句,ABS 并不是一个特别受好评的参考;它因在其示例中展示不良做法而臭名昭著。考虑wooleedge wiki(即BashFAQ #1,它在“我的文本文件已损坏!”部分明确涵盖了您的问题)或bash-hackers wiki
  • 哦,是的,我一直在使用 bash-hackers wiki,并且非常喜欢它。谢谢推荐。

标签: bash shell loops file-descriptor io-redirection


【解决方案1】:

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

$ 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多