[Zsh] 顯示指令執行時間
還是花了時間把 zsh
弄成自己想要的樣子:
https://github.com/pcwu/pcwu.zsh-theme
Execution Time
主要比較麻煩的是顯示指令的執行時間,需要去 hook preexec
和 precmd
:
autoload -Uz add-zsh-hook
add-zsh-hook preexec preexec
add-zsh-hook precmd precmd
preexec
Executed just after a command has been read and is about to be executed. If the history mechanism is active (regardless of whether the line was discarded from the history buffer), the string that the user typed is passed as the first argument, otherwise it is an empty string. The actual command that will be executed (including expanded aliases) is passed in two different forms: the second argument is a single-line, size-limited version of the command (with things like function bodies elided); the third argument contains the full text that is being executed.
precmd
Executed before each prompt. Note that precommand functions are not re-executed simply because the command line is redrawn, as happens, for example, when a notification about an exiting job is displayed.
所以就是要在 preexec
取得起始時間, precmd
獲得結束時間並算出時間差:
function preexec() {
timer=${timer:-$SECONDS}
}
function precmd() {
if [ $timer ]; then
timer_show=$(($SECONDS - $timer))
if [[ $timer_show -ge $min_show_time ]]; then
RPROMPT='%{$fg_bold[red]%}(${timer_show}s)%f%{$fg_bold[white]%}[%*]%f'
else
RPROMPT='%{$fg_bold[white]%}[%*]%f'
fi
unset timer
fi
}
大概就是這樣~