Display execution time for long-running commands

I'm often running programs that take a long time to execute.
Sometimes it's so long I'm leaving the puter to do other things and when I get back the command has completed but I'm not sure exactly when so the next time I run the command I still won't have an idea of how long it will take.

Granted, I could use the time command but I often forget to do that.

Found this trick this afternoon:

  • Download this file and save it to ~/.bash-preexec.sh

This will allow you to define bash hooks.

  • Edit your ~/.bashrc to source that file and define those hooks:
. ~/.bash-preexec.sh 

LASTCMDTIME=`date +%s`

function trackduration {
    t1=$LASTCMDTIME
    t2=$(date +%s)
    DURATION=$(expr $t2 - $t1)
    if [ $DURATION -gt 1 ]; then
        echo "[Execution took: $DURATION s]"
    fi
    LASTCMDTIME=$t2
}

function preexec() { LASTCMDTIME=`date +%s`; };
function precmd() { trackduration; }

4 Likes

Brilliant, thanks for sharing!