Is there a way to find the running time of the last executed command in the shell?

0

Issue

Is there a command like time that can display the running time details of the last or past executed commands on the shell?

Solution

I do not know, how it is in bash, but in zsh you can define preexec and precmd functions so that they save the current time to variables $STARTTIME (preexec) and $ENDTIME (precmd) so you will be able to find the approximate running time. Or you can define an accept-line function so that it will prepend time before each command.

UPDATE:
This is the code, which will store elapsed times in the $_elapsed array:

preexec () {
   (( $#_elapsed > 1000 )) && set -A _elapsed $_elapsed[-1000,-1]
   typeset -ig _start=SECONDS
}
precmd() { set -A _elapsed $_elapsed $(( SECONDS-_start )) }

Then if you run sleep 10s:

% set -A _elapsed # Clear the times
% sleep 10s
% sleep 2s ; echo $_elapsed[-1]
10
% echo $_elapsed
0 10 0

No need in four variables. No problems with names or additional delays. Just note that $_elapsed array may grow very big, so you need to delete the first items (this is done with the following piece of code: (( $#_elapsed > 1000 )) && set -A _elapsed $_elapsed[-1000,-1]).

UPDATE2:
Found the script to support zsh-style precmd and preexec in bash. Maybe you will need to remove typeset -ig (I used just to force $_start to be integer) and replace set -A var ... with var=( ... ) in order to get this working. And I do not know how to slice arrays and get their length in bash.

Script: http://www.twistedmatrix.com/users/glyph/preexec.bash.txt

UPDATE3:
Found one problem: if you hit return with an empty line preexec does not run, while precmd does, so you will get meaningless values in $_elapsed array. In order to fix this replace the precmd function with the following code:

precmd () {
   (( _start >= 0 )) && set -A _elapsed $_elapsed $(( SECONDS-_start ))
   _start=-1 
}

Answered By – ZyX

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More