下面是我写的一个脚本来说明这个问题:
#!/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
这是它的输出:
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
显然,可以通过首先保存流(在文件或变量中)并根据需要多次使用它来解决这个问题。但为什么会发生这种消费呢?
后来,我在Unix-StackExchange上发现这个问题与同一件事有关。它还包含值得一看的信息:Bash Reuse Process Substitution File
1条答案
按热度按时间baubqpgj1#
进程替换是使用管道实现的。被替换进程的输出由操作系统缓冲,并在读取后丢弃。所以
cat_then_tac <(seq 3)
在功能上等同于: