英文:
Why does process substitution streams can be read only once in bash?
问题
以下是翻译好的内容:
这是我编写的一个脚本,用于说明这个问题:
#!/bin/bash
cat_then_tac()
{
echo cat
cat "$1"
echo tac
tac "$1"
echo end
}
seq 3 > file1
echo
echo 使用正确的文件:按预期工作
cat_then_tac file1
echo
echo 使用进程替代:流在第一次使用时似乎被消耗掉,tac 没有可用的内容
cat_then_tac <(seq 3)
rm file1
这是它的输出:
使用正确的文件:按预期工作
cat
1
2
3
tac
3
2
1
end
使用进程替代:流在第一次使用时似乎被消耗掉,tac 没有可用的内容
cat
1
2
3
tac
end
显然,可以通过首先保存流(在文件或变量中)并多次使用它来解决这个问题。但为什么会发生这种消耗呢?
后来,我在Unix-StackExchange上找到了与相同问题相关的这个问题。它还包含值得一看的信息:
Bash 重复使用进程替代文件
英文:
Here's a script I wrote to illustrate the issue:
#!/bin/bash
cat_then_tac()
{
echo cat
cat "$1"
echo tac
tac "$1"
echo end
}
seq 3 > file1
echo
echo using proper file: works as expected
cat_then_tac file1
echo
echo using process substitution: stream is somehow consumed upon first use and tac has nothing to work on
cat_then_tac <(seq 3)
rm file1
And here's its output:
using proper file: works as expected
cat
1
2
3
tac
3
2
1
end
using process substitution: stream is somehow consumed upon first use and tac has nothing to work on
cat
1
2
3
tac
end
Obviously one can work around this by first saving the stream (in a file or variable) and using it as many times as needed. But why does this sort of consumption happen?
Later, I found this question on Unix-StackExchange related to the same matter. And it also contains info worth taking a look:
Bash Reuse Process Substitution File
答案1
得分: 5
Process substitution使用管道实现。替代进程的输出由操作系统缓冲并在读取后丢弃。因此,cat_then_tac <(seq 3)
与以下命令相同:
seq 3 | cat_then_tac -
英文:
Process substitution is implemented using pipes. The output of the substituted process is buffered by the operating system and discarded after it is read. So cat_then_tac <(seq 3)
is the same as
seq 3 | cat_then_tac -
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论