Hund

Display the time it took to run a command in zsh

Published: Tuesday, April 9, 2019

zsh-command-time is a neat little plugin for zsh that displays the time it took to run a command.

Here’s a demo:

$ sleep 5 ; echo "Every 60 seconds a minute passes in Africa."
Every 60 seconds a minute passes in Africa.

[ Time: 5s ]

Installation

Download the plugin via git to your preferable folder of choice:

$ git clone https://github.com/popstas/zsh-command-time

Add this line to your ~/.zshrc configuration file (and make sure that the path points to your file):

source "$HOME/.zsh/plugins/zsh-command-time/command-time.plugin.zsh"

This part is also going into your ~/.zshrc configuration file:

# Different output for zsh-command-time
zsh_command_time() {
    if [ -n "$ZSH_COMMAND_TIME" ]; then
        hours=$(($ZSH_COMMAND_TIME/3600))
        min=$(($ZSH_COMMAND_TIME/60))
        sec=$(($ZSH_COMMAND_TIME%60))
        if [ "$ZSH_COMMAND_TIME" -le 60 ]; then
            timer_show="$fg[green]${ZSH_COMMAND_TIME}s $fg[default]"
        elif [ "$ZSH_COMMAND_TIME" -gt 60 ] && [ "$ZSH_COMMAND_TIME" -le 180 ]; then
            timer_show="$fg[yellow]${min}m ${sec}s $fg[default]"
        else
            if [ "$hours" -gt 0 ]; then
                min=$(($min%60))
                timer_show="$fg[red]${hours}h ${min}m ${sec}s $fg[default]"
            else
                timer_show="$fg[red]${min}m ${sec}s"
            fi
        fi
        printf "\n[ ${ZSH_COMMAND_TIME_MSG}\n" "$timer_show]"
    fi
}

To prevent too much clutter in the main configuration file I added the above part to a file called ~/.zsh/functions.zsh. If you wish to do the same thing, don’t forget to source the file in your ~/.zshrc configuration file as well:

source "$HOME/.zsh/functions.zsh"

Source your configuration with $ source ~/.zshrc (or just restart the terminal emulator) when you’re done for the changes to take effect.


Meta

Comments

If you want to leave feedback you can do so by sending me a message via e-mail.