How can I automatically time commands in bash?

Solution 1:

I don't think you can achieve exactly the same effect without modifying the bash source. But you can get close, hopefully close enough for you.

You can combine bash's hacky precommand hook and the SECONDS variable to show the wall clock time in a non-intrusive way. Here's a simple implementation due to Ville Laurikari. The functions timer_start and timer_stop are executed immediately before starting a command and immediately before displaying the next prompt.

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]$ '

To get the full time information for every command, here's a way due to Dennis Williamson:

bind '"\C-j": "\C-atime {\C-e;}\C-m"'

When you press Ctrl+J instead of Enter to start a command, you'll get time information. Rebinding Enter (i.e. Ctrl+M) is not recommended because the modified command will sometimes be syntactically incorrect.

See How can the last command's wall time be put in the Bash prompt? and Automatically timing every executed command and show in Bash prompt? on Stack Overflow for other methods (note however that most only give the elapsed real time, not the CPU time).