Guest

Eduardo IdNotFound

By: a guest on Oct 13th, 2008  |  syntax: Bash  |  size: 1.42 KB  |  hits: 30  |  expires: Never
download  |  raw  |  embed  |  report abuse
Copied
  1. #
  2. # timelast  -  shows how long the last running command lasted
  3. # http://idnotfound.wordpress.com/2008/10/14/a-bash-plugin-timelast/
  4. #
  5.  
  6.  
  7. # this is the command called by the user
  8. timelast () {
  9.         # shows a pretty output like '1h23m45s'
  10.  
  11.         # how many seconds it took
  12.         ret="$(( $_timelast_time % 60 ))s"
  13.         cur=$(( $_timelast_time / 60 ))
  14.  
  15.         # tests for minutes
  16.         if [ $cur -gt 0 ]; then
  17.                 ret="$(( $cur % 60 ))m${ret}"
  18.                 cur=$(( $cur / 60 ))
  19.         fi
  20.  
  21.         # tests for hours
  22.         if [ $cur -gt 0 ]; then
  23.                 ret="${cur}h${ret}"
  24.         fi
  25.  
  26.         # echoes on the screen
  27.         echo $ret
  28.         return 0
  29. }
  30.  
  31.  
  32. # internal command that calculates the running time of the last process
  33. # (add to $PROMPT_COMMAND, so it is executed at each prompt -- see below)
  34. _timelast_promptcommand () {
  35.         # grab the timestamp of the last command from history
  36.         # (depends on $HISTTIMEFORMAT="%s " -- see below)
  37.         _timelast_start="$(history | tail -n1 | awk '{ print $2 }')"
  38.  
  39.         # now grab the timestamp for the current time
  40.         _timelast_end="$(date +%s)"
  41.  
  42.         # subtract and... voila! elapsed seconds! :-)
  43.         _timelast_time="$(( $_timelast_end - $_timelast_start ))"
  44.  
  45.         return 0
  46. }
  47.  
  48.  
  49. ## sets up initial values and important variables in bash
  50.  
  51. # timestamps the command history so we know when commands were performed
  52. export HISTTIMEFORMAT="%s "
  53.  
  54. # calculates how long the last command ran for at every prompt shown
  55. export PROMPT_COMMAND="_timelast_promptcommand; ${PROMPT_COMMAND}"