Bash 时间表现得很奇怪

Bash 时间表现得很奇怪

为什么这不起作用?

$ time sleep 1 2>&1 | grep real

real    0m1.003s
user    0m0.007s
sys 0m0.001s

$ ofile=time.out
$ for x in {1..2}; do time sleep 1 ${x}> ${ofile} && test -s ${ofile} && echo '## OK' || echo '## NOK'; done

real    0m2.002s
user    0m0.002s
sys 0m0.000s
## NOK

real    0m3.002s
user    0m0.002s
sys 0m0.000s
## NOK

根据man time

当命令完成时,时间会向标准错误写入一条消息,提供有关此程序运行的计时统计信息。

我哪里弄错了?随着每次迭代时间的增长,这似乎也很奇怪?

$ command -V time
time is a shell keyword

$ echo $SHELL
/bin/bash

$ bash --version
GNU bash, version 4.4.12(1)-release (x86_64-unknown-linux-gnu)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

编辑

我尝试了评论中的建议:

$ command time sleep 1
bash: time: command not found

也在Debian9系统上测试了一下:

$ command -V time 
time is a shell keyword

$ command time sleep 1
0.00user 0.00system 0:01.00elapsed 0%CPU (0avgtext+0avgdata 1844maxresident)k
0inputs+0outputs (0major+76minor)pagefaults 0swaps

$ time sleep 1 |& grep real

real    0m1.001s
user    0m0.000s
sys 0m0.000s

$ bash --version
GNU bash, version 4.4.12(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

答案1

您的命令time sleep 1 ${x}有效运行time sleep 1 1,然后time sleep 1 2.

bash内置命令time采用这两个值并为它们休眠。

所以sleep 1 1与 相同sleep 2sleep 1 2与 相同sleep 3

使用内置time命令,事情的工作方式与正常情况不太一样,因此time sleep 2>...解释更接近time ( sleep 2>...).

所以与其

( time sleep 1 ) 2>&1 | grep real

相关内容