如何在 bash 中自动计时命令?

Eya*_*yal 14 bash time-command

tcsh,有变量time

   The time shell variable can be set to execute the time builtin command
   after the completion of any process that takes more than a given number
   of CPU seconds.
Run Code Online (Sandbox Code Playgroud)

我如何做到这一点bash

Gil*_*il' 14

我不认为你可以在不修改 bash 源代码的情况下达到完全相同的效果。但是你可以接近,希望对你来说足够接近。

您可以将bash 的 hacky precommand 钩子SECONDS变量结合起来,以非侵入性的方式显示挂钟时间。这是Ville Laurikari的一个简单实现。函数timer_start和函数timer_stop在开始命令之前和显示下一个提示之前立即执行。

function timer_start {
  timer=${timer:-$SECONDS}
}
function timer_stop {
  timer_show=$(($SECONDS - $timer))
  unset timer
}
trap 'timer_start' DEBUG
PROMPT_COMMAND=timer_stop
PS1='[last: ${timer_show}s][\w]$ '
Run Code Online (Sandbox Code Playgroud)

为了获得time每个命令的完整信息,这里有一种方法归功于丹尼斯威廉姆森

bind '"\C-j": "\C-atime {\C-e;}\C-m"'
Run Code Online (Sandbox Code Playgroud)

当您按Ctrl+J而不是Enter启动命令时,您将获得时间信息。不建议重新绑定Enter(即Ctrl+ M),因为修改后的命令有时会在语法上不正确。

请参阅如何将最后一个命令的挂墙时间放在 Bash 提示符中?自动计时每个执行的命令并显示在 Bash 提示中?关于其他方法的堆栈溢出(但请注意,大多数只提供经过的实时时间,而不是 CPU 时间)。