解决方案
使用绝对路径
/usr/bin/time
而不是直接使用 time 命令。
问题描述
有时候需要用 time 命令统计一下命令的耗时与占用,例如:
time curl https://www.youkuaiyun.com > /dev/null
➜ ~ time curl https://www.youkuaiyun.com > /dev/null
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 1149k 100 1149k 0 0 1052k 0 0:00:01 0:00:01 --:--:-- 1052k
curl https://www.youkuaiyun.com > /dev/null 0.01s user 0.01s system 1% cpu 1.101 total
如果有统计或其他用途,需要格式化 time 的输出结果,通过 man time 了解一下怎么格式化:

只需要实际时间,于是在 time 命令后加上了参数 -f '%e'
➜ ~ time -f '%e' curl https://www.youkuaiyun.com > /dev/null
zsh: command not found: -f
-f '%e' curl https://www.youkuaiyun.com > /dev/null 0.00s user 0.00s system 73% cpu 0.001 total
执行后发现,追加在 time 后面的参数 -f 被当作命令尝试执行了,当然这个命令不存在。
再仔细看看 man time 里面的内容:

对于 bash 等 Shell(例如本文的 zsh),需要使用绝对路径指定 time 命令。
通过 which 命令可以看到 time 是 shell 的保留字。
➜ ~ which time
time: shell reserved word
使用正确的方式重新执行:
➜ ~ /usr/bin/time -f '%e' curl --no-progress-meter https://www.youkuaiyun.com > /dev/null
1.25
输出了格式化后的结果。

当需要格式化time命令的输出时,直接使用time可能会导致参数被误解析为新命令。解决方法是在bash或zsh等Shell中使用绝对路径/usr/bin/time,并结合-f选项来指定输出格式。例如,使用/usr/bin/time -f'%e'命令可以仅显示执行时间。此方法适用于需要精确控制time命令输出格式的场景。
569

被折叠的 条评论
为什么被折叠?



