Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: time command with shell builtins



On Thu, Feb 02, 2023 at 10:28:36AM -0800, Bart Schaefer wrote:
> On Thu, Feb 2, 2023 at 10:10 AM Dominik Vogt <dominik.vogt@xxxxxx> wrote:
> >
> > Well, is there a way to detect inside preexec() wether a command
> > is handled by the shell or some external binary?
>
> If you actually have the command name, you can use
>   if (( $+commands[$thename] ))
>
> That won't work (or will be complicated) if the buffer that's about to
> be executed is a complex structure (braces, subshell parens,
> while/for/repeat/if/case/select/etc.).

Okay, that sounds good enough.  The new solution works without a
blacklist.  It may still print statistics with REPORTTIME and on
the prompt in some cases (e.g. "{ /usr/bin/foobar" }" etc.).  But
I can live with that.  Note that it now uses two slots in the
psvar array.  In some scenarios with ctrl-c using psvar[2] for the
raw time and the string to print resulted in error messages
because the variable's value was just ' s'.

-- snip --
autoload -Uz add-zsh-hook
zmodload zsh/datetime
function preexec_recordtime() {
	local CL=( $3 )
	psvar[3]=''
	if (( $+commands[${CL[1]}] )); then
		psvar[2]=''
	elif [[ -n $REPORTTIME ]]; then
		psvar[2]="$EPOCHSECONDS"
	else
		psvar[2]=''
	fi
}
precmd_reporttime () {
	if [[ -n "$REPORTTIME" && -n "$psvar[2]" ]]; then
		psvar[2]=$(( $EPOCHSECONDS - $psvar[2] ))
		if (( $psvar[2] <= $REPORTTIME )); then
			psvar[3]=''
		else
			psvar[3]=" $psvar[2]s"
		fi
	fi
}
add-zsh-hook preexec preexec_recordtime
add-zsh-hook precmd precmd_reporttime
PS1="...%3v..."
-- snip --

Ciao

Dominik ^_^  ^_^

--

Dominik Vogt




Messages sorted by: Reverse Date, Date, Thread, Author