Linux time 命令怎么接不了参数?

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解决方案

使用绝对路径

/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

输出了格式化后的结果。

参考资料:
Why doesn’t the time command work with any option?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wuweijie@apache.org

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值