Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zsh: print time next to command on execute

Tags:

zsh

I want to configure zsh to append the time each command started next to the line command was executed on. For example:

# before I press ENTER
$ ./script

# after I press enter
$ ./script [15:55:58]
Running script...

I came up with the following config (which also colors the timestamp yellow):

preexec () {
  TIME=`date +"[%H:%M:%S] "`
  echo -e "$1 %{$fg[yellow]%}\033[1A\033[1C${TIME}$reset_color"
}

But it breaks and prints { and % characters on basic commands such as cat and echo. It also breaks on password prompts (macOS terminal). For example with echo:

$ echo "hello" [15:55:58] 
hello"hello" %{%}

How can I fix this config? Thank you.

like image 741
deterjan Avatar asked Oct 31 '25 03:10

deterjan


1 Answers

In your ~/.zshrc file, put:

function preexec() {
  timer=${timer:-$SECONDS}
}

function precmd() {
  if [ $timer ]; then
    timer_show=$(($SECONDS - $timer))
    export RPROMPT="%F{cyan}${timer_show}s %F{$black%}"
    unset timer
  fi
}

And that should give you something like this: enter image description here

like image 59
Christopher Settles Avatar answered Nov 04 '25 06:11

Christopher Settles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!