Search code examples
cshtcsh

How to set my tcsh prompt to show the execution time of the previous command?


I am using tcsh at work and would really appreciate knowing how long the execution of a command took place.

For example:

~
❯ sleep 55

~ took 55s
❯

Solution

  • Just use the time command.

    > time sleep 55
    0.001u 0.000s 0:55.01 0.0%  0+0k 0+0io 0pf+0w
    

    EDIT:

    I hadn't noticed the title. To do that for every command, you can use the precmd, postcmd aliases along with the date command

    alias postcmd 'set start_time=`date +%s`'
    alias precmd 'set end_time=`date +%s`; @ cmd_time= $end_time - $start_time; echo took $cmd_time seconds'
    

    Run both these commands, or add them to ~/.cshrc if you want this to be default behavior. The output would be like this:

    > time sleep 55
    took 55 seconds
    

    Explanation:

    postcmd: Runs before each command gets executed.

    precmd: Runs just before each prompt is printed (after the command runs).

    date +%s: Prints time in raw seconds format.

    I simply saved the raw seconds value in the variables start_time and end_time, then saved the difference in cmd_time and printed it.