我有这个:
tee < /some/big/file >(wc -c) >(md5sum) | ...
我不想将 wc -c
和 md5sum
的结果写入 stdout,而是将结果存储到两个变量中以供以后处理。我不想多次读取该文件。我怎样才能做到这一点?
最佳答案
这并不能直接回答您的问题...但您只需读取该文件一次,并且不必使用 tee
.
SIZE=$(wc -c /some/big/file)
MD5=$(md5 /some/big/file)
那么,这会读取文件多少次?一次。这是因为wc -c
实际上并不读取文件,它只是查看文件的长度并返返回告。这是我的测试:
$ time wc -c /big/file >/dev/null
real 0m0.003s
user 0m0.000s
sys 0m0.000s
$ time wc -c </big/file >/dev/null
real 0m0.004s
user 0m0.000s
sys 0m0.000s
$ time cat /big/file | wc -c >/dev/null
real 0m52.945s
user 0m0.160s
sys 0m19.612s
教训:不要混合tee
(或 cat
)与 wc -c
,因为这是一个很大的时间浪费。只需执行 md5
通常情况下,不用担心wc -c
.
注:原因wc -c <file
之所以快是因为它获得一个普通的文件句柄,就像wc
一样曾调用open()
本身。
管道性能
你几乎不应该使用cat
在管道中。
cat file | cmd # slow
cmd <file # fast
调用cat
通常意味着创建一个没有任何目的的额外进程。在某些情况下,如 wc -c
,它实际上减慢了管道后的程序速度。我的意思是,你可以坚持 cat
任何你喜欢的地方,但这很愚蠢:
echo 'hello, world' | cat
cat file.txt | less
cat file.txt | cat | less
cat file.txt | cat | sort | cat | cat | uniq | cat >file_unique.txt
这样更好:
echo 'hello, world'
less file.txt
sort file.txt | uniq >file_unique.txt
关于bash - 如何将 >() 内 Bash 命令的输出存储在变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16473767/