【问题标题】:Suppress output of a command while recording output from "time"在记录“时间”的输出时抑制命令的输出
【发布时间】:2019-05-06 04:45:32
【问题描述】:

我有一些以这种方式启动的命令:

./mycommand -arg=word

我测量执行时间并将输出写入文件:

/usr/bin/time -f "%K %e" ./mycommand -arg=word 2>file

但是,mycommand 也有 stderr 输出。所以file 包含来自两者(timemycommand)的混合数据。如何抑制mycommand 输出并保存time 数据?

【问题讨论】:

  • BashFAQ 中有一个关于此的条目。也就是说,如果你使用 shell 内置时间,而不是 /usr/bin/time,会更容易。
  • @CharlesDuffy time -f "%R" ls 给我-f: command not found
  • 是的,这就是我在建议使用 shell-builtin time 而不是操作系统的答案分支中使用 TIMEFORMAT 变量而不是 -f 参数的原因- 提供了一个。

标签: bash output stderr


【解决方案1】:

如果你的进程的性质是 shell 启动不会过多干扰时间,一种简单的方法是让 shell 作为 time 的子进程运行方向:

/usr/bin/time -f "%K %e" sh -c '"$0" "$@" >/dev/null 2>&1' ./mycommand -arg=word

我还建议使用 bash 内置版本的 time 而不是外部版本,这样您就可以使用 BashFAQ #32 中记录的技巧:

TIMEFORMAT='%R' # replace for whatever is equivalent to your "%K %e"
timing=$(time { ./mycommand >/dev/null 2>&1; } 2>&1)

【讨论】:

  • sh -c '' 是否更改相对路径?现在arg由于相对路径无法识别
  • 它给了我一个错误 ./mycommand: 1: ./mycommand: -arg=word: not found
  • 不,sh -c 不会更改路径(除非您有一个 ENV 变量指向更改目录的脚本)。
  • ...也就是说,这里的错误是由$0 使用命令名引起的,而将其排除在"$@" 之外;查看解决该问题的修改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-05
  • 1970-01-01
  • 2021-12-03
  • 2012-07-12
  • 1970-01-01
  • 2021-06-06
  • 2011-03-03
相关资源
最近更新 更多