在 bash 脚本中使用时间:如何获得“正常”时间输出?
如果我在 shell 中使用 time
,我会得到类似的输出
$ time sleep 1
real 0m1.003s
user 0m0.000s
sys 0m0.000s
但是,如果我在 bash 脚本中使用相同的命令,输出就是
0.00user 0.00system 0:01.00elapsed 0%CPU (0avgtext+0avgdata 2176maxresident)k
0inputs+0outputs (0major+179minor)pagefaults 0swaps
我已经找到的 这篇文章,但是我想要的是使用time
在脚本中,同时仍然获得与在 shell 中使用它相同的输出。
If I use time
in the shell, I get an output like
$ time sleep 1
real 0m1.003s
user 0m0.000s
sys 0m0.000s
However, if I use the same command in a bash script, the output is this
0.00user 0.00system 0:01.00elapsed 0%CPU (0avgtext+0avgdata 2176maxresident)k
0inputs+0outputs (0major+179minor)pagefaults 0swaps
I already found this post, but what I want is to use time
in a script, while still getting the same output as if I was using it in a shell.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
...是 GNU 版本的外部
time
生成的默认输出命令。...是
bash
内置时间
。time
的此内置版本是bash
扩展:POSIX 兼容 shell 不需要提供内置版本的time
。但是,POSIX 确实指定了一个外部
time
实用程序,它可以使用-p
选项来生成另一种输出格式:...并且
bash
内置函数也接受-p
选项产生相同的输出格式。bash
内置函数应该在 shell 脚本中完美运行,只要该脚本实际上由bash
运行:因此看来您的脚本正在调用外部实用程序而不是内置的
bash
。最可能的原因是:
#!/bin/sh
而不是#!/bin/bash
;并且/bin/sh
实际上并不是bash
,而是一个更轻量级的 POSIX 兼容 shell,没有bash
扩展(如发现现在在一些 Linux 发行版上)。解决方案是确保脚本在依赖
bash
扩展时使用#!/bin/bash
专门调用bash
。...is the default output produced by the GNU version of the external
time
command....is the default output produced by the
bash
builtintime
. This builtin version oftime
is abash
extension: a POSIX-compliant shell is not required to provide a builtin version oftime
.However, POSIX does specify an external
time
utility, which can take-p
option to produce yet another output format:...and the
bash
builtin also accepts the-p
option to produce the same output format.The
bash
builtin should work perfectly well in a shell script provided the script is actually being run bybash
:So it seems that your script is invoking the external utility rather than the
bash
builtin.The most likely cause of this is that:
#!/bin/sh
rather than#!/bin/bash
; and/bin/sh
on your machine is not actuallybash
, but a more lightweight POSIX-compliant shell without thebash
extensions (as found on some Linux distributions these days).The solution is to ensure that the script specifically invokes
bash
by using#!/bin/bash
if it relies onbash
extensions.您尝试过
-p
标志吗?Did you try the
-p
flag?不同之处在于,通过管道传输时输出不会到达终端。
完成良好布局所需的终端代码不适用于文件流。
你想实现什么目标?如果您想要“屏幕截图”,请查看
脚本
The difference is that output is not going to terminal when piped.
The terminal codes necessary to do the nice layout do not work on a filestream.
What did you want to achieve? If you intend to have the 'screenshot' have a look at
script