【问题标题】:Pipe stderr and stdout separately in bash/sh [duplicate]在 bash/sh 中分别管道 stderr 和 stdout [重复]
【发布时间】:2014-02-22 01:51:08
【问题描述】:

我一直在尝试在我的服务器上使用以下命令 dd if=/dev/zero bs=1M count=1024 | md5sum

输出:

1024+0 records in
1024+0 records out
1073741824 bytes (1.1 GB) copied, 2.92245 s, 367 MB/s
cd573cfaace07e7949bc0c46028904ff  -

如何让它仅将速度 (367 MB/s) 显示为输出?状态打印到stderr

我目前正在使用awk,但它显示了 md5 哈希。

感谢您的帮助:)

【问题讨论】:

  • 需要md5sum吗?还是of=/dev/null 也足够了?
  • @Carpetsmoker 是的,我需要 md5sum。
  • 您需要速度还是哈希?
  • 我不确定这个命令的目的是什么。您肯定不会测试 MD5 计算速度,而是测试从 /dev/zero (或任何其他来源)读取的速度。你确定| md5sum 完全相关吗?
  • @Carpetsmoker +1。使用临时文件很容易,但是没有它就很复杂。

标签: linux bash shell dd


【解决方案1】:

首先,一个模拟你的命令的函数

simulation() { 
  echo "1024+0 records in
1024+0 records out
1073741824 bytes (1.1 GB) copied, 2.92245 s, 367 MB/s" >&2
  echo "cd573cfaace07e7949bc0c46028904ff  -"
}

$ simulation >/dev/null
1024+0 records in
1024+0 records out
1073741824 bytes (1.1 GB) copied, 2.92245 s, 367 MB/s

$ simulation 2>/dev/null
cd573cfaace07e7949bc0c46028904ff  -

然后,解决方案:将 stderr 重定向到将所需输出显示回 stderr 的进程替换,在变量中捕获 stdout。

$ md5sum=$( simulation 2> >(sed -n '/MB\/s/ {s/.*, //p; q}' >&2) )
367 MB/s

$ echo $md5sum
cd573cfaace07e7949bc0c46028904ff -

【讨论】:

  • 为了澄清,您需要将simulation 替换为仅dd 命令,并将| md5sum 放在最后一个右括号之前,即:@987654326 @
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-30
  • 1970-01-01
  • 2011-04-07
  • 1970-01-01
  • 2015-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多