bash - 使用 fd 嵌套 while 读取循环

标签 bash shell loops file-descriptor io-redirection

我试图在嵌套循环中读取两个不同的输入,但没有成功。我遵循了最佳答案 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/

相关文章:

python - 从 Bash 导入 Python 模块

bash - 递归重命名文件夹/目录

java - 使用 Java 运行 .sh

bash - 在 shell 中生成带有一个特殊字符的随 secret 码

linux - 编写 Shell 脚本 - 可以打印错误并可以继续保留您刚刚在命令行中运行的输入

java - java中如何将整数存储到字符串多维数组中

python - 唯一计算相邻两行的百分比差异

shell - 如何使用 C 程序的选项运行 'ls'?

java - 如何为输入错误日期的用户正确创建循环?

c - Lua 键名或自动索引?