努力解析(bash)时间命令 [英] Struggling to parse (bash) time command

查看:19
本文介绍了努力解析(bash)时间命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力解析 bash 中 time 命令的输出 - 甚至在我调用它时阻止它打印输出.这是我的测试代码:

I'm struggling to parse the output of the time command in bash - and even to stop it from printing out its output when I call it. This is my test code:

#!/bin/bash
TIME=`time ls -lh > /dev/null`
echo "Testing..."
echo $TIME

当前打印出来:

{blank-line}
real    0m0.064s
user    0m0.002s
sys     0m0.005s
Testing
{blank-line}

因此,分配给 $TIME 的值似乎是时间打印开始处的空行.我需要获取 sys 行的秒值 - 即0.005".我保证我只有几秒钟,所以在m"之前我不需要任何东西 - 但是,如果它>= 10 秒,秒部分可能采用 xx.xxx 的形式.我目前不知道如何抑制时间"输出,捕获它而不是空行,也不知道如何解析它以获得我需要的值.

So, it seems like the value assigned to $TIME is the blank line at the start of the time print-out. I need to get at the seconds value of the sys line - that is, the "0.005". I am guaranteed that I will only ever have seconds, so I do not need anything before the "m" - however, the seconds part may be in the form of xx.xxx if it goes >= 10 seconds. I currently have no idea how to suppress the 'time' output, capture it all instead of the blank line, nor parse it to get the values I need.

任何帮助将不胜感激...

Any help would be much appreciated...

推荐答案

如果你使用 Bash 内置的 time,你可以通过设置 TIMEFORMAT 变量来控制它的输出:

If you use the Bash builtin time, you can control its output by setting the TIMEFORMAT variable:

TIMEFORMAT=%R

并且您不必进行任何解析,因为这会导致 time 仅输出秒数.

and you won't have to do any parsing since that will cause time to only output the number of seconds.

并使用这个:

echo "Testing..."
TIME=$( { time ls -lh > /dev/null; } 2>&1 )
echo $TIME

BashFAQ/032 中的其他技术之一.

or one of the other techniques from BashFAQ/032.

这篇关于努力解析(bash)时间命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆